package com.aizuda.boot.modules.business.approval.service.impl;

import com.aizuda.boot.modules.business.approval.entity.dto.TaskCenterQueryDTO;
import com.aizuda.boot.modules.business.approval.entity.vo.PendingApprovalTaskVO;
import com.aizuda.boot.modules.business.approval.service.TaskCenterService;
import com.aizuda.boot.modules.business.contract.dto.UserInfo;
import com.aizuda.boot.modules.business.contract.entity.ContractEntity;
import com.aizuda.boot.modules.business.contract.entity.ContractFieldEntity;
import com.aizuda.boot.modules.business.contract.entity.ContractFieldValueEntity;
import com.aizuda.boot.modules.business.contract.mapper.ContractFieldValueMapper;
import com.aizuda.boot.modules.business.contract.mapper.ContractMapper;
import com.aizuda.boot.modules.business.contract.service.ContractFieldService;
import com.aizuda.boot.modules.business.contract.util.AuthUtil;
import com.aizuda.boot.modules.business.negotiation.entity.ContractNegotiationInstanceEntity;
import com.aizuda.boot.modules.business.negotiation.mapper.ContractNegotiationInstanceMapper;
import com.aizuda.boot.modules.common.constant.enums.SystemFieldsEnum;
import com.aizuda.boot.modules.flw.entity.FlwProcessCategory;
import com.aizuda.boot.modules.flw.entity.FlwProcessConfigure;
import com.aizuda.boot.modules.flw.entity.dto.ProcessInfoDTO;
import com.aizuda.boot.modules.flw.entity.dto.ProcessTaskDTO;
import com.aizuda.boot.modules.flw.entity.vo.TaskApprovalVO;
import com.aizuda.boot.modules.flw.mapper.FlowlongMapper;
import com.aizuda.boot.modules.flw.mapper.FlwProcessCategoryMapper;
import com.aizuda.boot.modules.flw.mapper.FlwProcessConfigureMapper;
import com.aizuda.boot.modules.flw.service.IFlwProcessTaskService;
import com.aizuda.boot.modules.system.entity.SysDepartment;
import com.aizuda.boot.modules.system.entity.SysUser;
import com.aizuda.boot.modules.system.entity.SysUserDepartment;
import com.aizuda.boot.modules.system.mapper.SysDepartmentMapper;
import com.aizuda.boot.modules.system.mapper.SysUserMapper;
import com.aizuda.boot.modules.system.service.ISysUserDepartmentService;
import com.aizuda.bpm.engine.FlowLongEngine;
import com.aizuda.bpm.engine.core.enums.ProcessType;
import com.aizuda.bpm.engine.entity.FlwHisInstance;
import com.aizuda.bpm.engine.entity.FlwHisTask;
import com.aizuda.bpm.engine.entity.FlwInstance;
import com.aizuda.bpm.engine.entity.FlwProcess;
import com.aizuda.bpm.engine.entity.FlwTask;
import com.aizuda.bpm.engine.entity.FlwTaskActor;
import com.aizuda.bpm.mybatisplus.mapper.FlwHisTaskMapper;
import com.aizuda.bpm.mybatisplus.mapper.FlwTaskActorMapper;
import com.aizuda.core.api.PageParam;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
import java.util.function.Function;

/**
 * 任务中心服务实现类
 */
@Service
@Slf4j
public class TaskCenterServiceImpl implements TaskCenterService {

    /**
     * 合同信息包装类，包含合同ID和审批类型
     */
    private static class ContractInfo {
        private Integer contractId;
        private String approvalType;
        
        public ContractInfo(Integer contractId, String approvalType) {
            this.contractId = contractId;
            this.approvalType = approvalType;
        }
        
        public Integer getContractId() {
            return contractId;
        }
        
        public String getApprovalType() {
            return approvalType;
        }
    }
    
    @Resource
    private FlwTaskActorMapper flwTaskActorMapper;
    
    @Resource
    private ContractMapper contractMapper;
    
    @Resource
    private ContractNegotiationInstanceMapper contractNegotiationInstanceMapper;
    
    @Resource
    private ContractFieldValueMapper contractFieldValueMapper;
    
    @Resource
    private SysDepartmentMapper sysDepartmentMapper;
    
    @Resource
    private SysUserMapper sysUserMapper;
    
    @Resource
    private ISysUserDepartmentService sysUserDepartmentService;
    
    @Resource
    private FlwProcessCategoryMapper flwProcessCategoryMapper;
    
    @Resource
    private FlwProcessConfigureMapper flwProcessConfigureMapper;
    
    @Resource
    private FlowLongEngine flowLongEngine;

    @Resource
    private IFlwProcessTaskService flwProcessTaskService;

    @Resource
    private FlwHisTaskMapper flwHisTaskMapper;

    @Resource
    private FlowlongMapper flowlongMapper;

    @Resource
    private ContractFieldService contractFieldService;

    /**
     * 根据字段代码获取字段ID
     * @param fieldCode 字段代码
     * @return 字段ID，如果未找到则返回null
     */
    private Long getFieldIdByCode(String fieldCode) {
        try {
            // 这里需要调用相应的服务来根据fieldCode获取fieldId
            // 假设有一个fieldService可以根据code获取ID
            // 由于没有看到具体的实现，这里使用一个简单的映射逻辑
            return mapFieldCodeToId(fieldCode);
        } catch (Exception e) {
            log.warn("根据字段代码获取字段ID失败: {}", fieldCode, e);
            return null;
        }
    }

    /**
     * 将字段代码映射为字段ID
     * @param fieldCode 字段代码
     * @return 字段ID
     */
    private Long mapFieldCodeToId(String fieldCode) {
        try {
            ContractFieldEntity field = contractFieldService.getOne(
                    Wrappers.<ContractFieldEntity>lambdaQuery()
                            .eq(ContractFieldEntity::getCode, fieldCode)
                            .select(ContractFieldEntity::getId)
                            .last("limit 1")
            );
            return field != null ? field.getId() : null;
        } catch (Exception e) {
            log.error("根据字段代码获取字段ID失败，字段代码: {}", fieldCode, e);
            return null;
        }
    }

    @Override
    public Page<PendingApprovalTaskVO> getPendingApprovalTasks(TaskCenterQueryDTO queryDTO, Long userId) {
        long current = queryDTO.getCurrent();
        long size = queryDTO.getSize();
        String keyword = queryDTO.getKeyword();
        String sortOrder = queryDTO.getSortOrder();

        log.info("获取用户 {} 的待审批任务列表，第 {} 页，每页 {} 条，关键词: {}，排序: {}", userId, current, size, keyword, sortOrder);

        try {
            // 获取当前用户的租户信息 - 修改逻辑：优先使用当前租户，如果为空则使用租户列表
            UserInfo currentUser = AuthUtil.getCurrentUser();
            String currentSysTenantKey = currentUser != null ? currentUser.getSysTenantKey() : null;
            List<String> userTenantKeys;

            if (currentSysTenantKey != null && !currentSysTenantKey.trim().isEmpty()) {
                // 如果当前用户有明确的sysTenantKey，只查询该租户下的数据
                userTenantKeys = List.of(currentSysTenantKey);
                log.info("待审批任务查询 - 使用当前租户过滤，租户键: {}", currentSysTenantKey);
            } else {
                // 如果sysTenantKey为null或空，使用原有逻辑（查询用户有权限的所有租户）
                userTenantKeys = AuthUtil.getUserTenantKeys();
                log.info("待审批任务查询 - 使用租户列表过滤，租户键列表: {}", userTenantKeys);
            }

            // 1. 直接查询 flw_task_actor 表，找到当前用户的所有待处理任务
            List<FlwTaskActor> taskActors = flwTaskActorMapper.selectList(
                Wrappers.<FlwTaskActor>lambdaQuery()
                    .eq(FlwTaskActor::getActorId, userId.toString())
                    .eq(FlwTaskActor::getActorType, 0) // 0表示用户类型
            );
            log.info("从 flw_task_actor 表查询到用户 {} 的任务数量: {}", userId, taskActors.size());

            if (taskActors.isEmpty()) {
                log.info("用户 {} 没有待审批任务", userId);
                return new Page<>(current, size, 0);
            }

            // 2. 获取所有任务对应的实例ID
            List<Long> instanceIds = taskActors.stream()
                .map(FlwTaskActor::getInstanceId)
                .distinct()
                .collect(Collectors.toList());

            log.info("涉及的流程实例ID数量: {}", instanceIds.size());

            // 3. 查询流程实例信息，过滤出 business 和 child 类型的流程
            List<Map<String, Object>> instancesWithProcess = contractMapper.selectInstancesWithProcessType(instanceIds);

            // 过滤出 business 和 child 类型的实例
            List<Map<String, Object>> validInstances = instancesWithProcess.stream()
                .filter(instance -> {
                    String processType = (String) instance.get("process_type");
                    return "business".equals(processType) || "child".equals(processType);
                })
                .collect(Collectors.toList());

            log.info("过滤后的有效实例数量（business/child类型）: {}", validInstances.size());

            if (validInstances.isEmpty()) {
                log.info("没有找到 business 或 child 类型的流程实例");
                return new Page<>(current, size, 0);
            }

            // 4. 提取有效的实例ID和对应的合同ID（通过business_key）
            List<Long> validInstanceIds = new ArrayList<>();
            List<Integer> contractIds = new ArrayList<>();

            for (Map<String, Object> instance : validInstances) {
                Long instanceId = Long.valueOf(instance.get("instance_id").toString());
                Object businessKeyObj = instance.get("business_key");

                if (businessKeyObj != null) {
                    try {
                        Integer contractId = Integer.valueOf(businessKeyObj.toString());
                        validInstanceIds.add(instanceId);
                        contractIds.add(contractId);
                    } catch (NumberFormatException e) {
                        log.warn("无效的 business_key: {}, instanceId: {}", businessKeyObj, instanceId);
                    }
                }
            }

            log.info("有效的实例ID数量: {}, 对应的合同ID数量: {}", validInstanceIds.size(), contractIds.size());

            if (contractIds.isEmpty()) {
                log.info("没有找到有效的合同ID");
                return new Page<>(current, size, 0);
            }
            
            // 5. 查询合同信息并应用租户隔离
            LambdaQueryWrapper<ContractEntity> contractQueryWrapper = Wrappers.<ContractEntity>lambdaQuery()
                .in(ContractEntity::getId, contractIds);

            // 应用租户隔离
            if (userTenantKeys != null && !userTenantKeys.isEmpty()) {
                contractQueryWrapper.in(ContractEntity::getSysTenantKey, userTenantKeys);
                log.info("应用多租户隔离过滤，租户键列表: {}", userTenantKeys);
            } else if (userTenantKeys != null) {
                contractQueryWrapper.eq(ContractEntity::getSysTenantKey, "NO_PERMISSION");
                log.warn("用户没有任何租户权限");
            }

            List<ContractEntity> contracts = contractMapper.selectList(contractQueryWrapper);
            log.info("租户隔离后查询到合同数量: {}", contracts.size());

            if (contracts.isEmpty()) {
                log.info("租户隔离后没有找到合法的合同记录");
                return new Page<>(current, size, 0);
            }

            // 6. 创建合同ID到合同对象的映射
            Map<Integer, ContractEntity> contractMap = contracts.stream()
                .collect(Collectors.toMap(ContractEntity::getId, contract -> contract));
            Set<Integer> validContractIds = contractMap.keySet();

            // 7. 过滤任务，只保留有效合同对应的任务
            List<FlwTaskActor> validTaskActors = taskActors.stream()
                .filter(taskActor -> validInstanceIds.contains(taskActor.getInstanceId()))
                .collect(Collectors.toList());

            log.info("过滤后的有效任务数量: {}", validTaskActors.size());
            
            // 8. 查询合同字段值
            List<ContractFieldValueEntity> fieldValues = contractFieldValueMapper.selectList(
                Wrappers.<ContractFieldValueEntity>lambdaQuery()
                    .in(ContractFieldValueEntity::getContractId, validContractIds)
                    .in(ContractFieldValueEntity::getFieldCode, List.of(
                        SystemFieldsEnum.CONTRACT_NAME.getCode(),
                        SystemFieldsEnum.CONTRACT_NUMBER.getCode(),
                        SystemFieldsEnum.APPLY_PEOPLE.getCode()
                    ))
            );

            Map<Integer, Map<String, String>> contractFieldMap = fieldValues.stream()
                .collect(Collectors.groupingBy(
                    ContractFieldValueEntity::getContractId,
                    Collectors.toMap(
                        ContractFieldValueEntity::getFieldCode,
                        ContractFieldValueEntity::getFieldValue
                    )
                ));

            // 9. 构建结果列表
            List<PendingApprovalTaskVO> resultList = new ArrayList<>();

            for (FlwTaskActor taskActor : validTaskActors) {
                try {
                    // 通过 business_key 找到对应的合同ID
                    Integer contractId = findContractIdByInstanceId(taskActor.getInstanceId(), validInstances);
                    if (contractId != null && contractMap.containsKey(contractId)) {
                        PendingApprovalTaskVO vo = buildPendingApprovalTaskVOFromTaskActor(
                            taskActor, contractId, contractMap.get(contractId), contractFieldMap);
                        if (vo != null) {
                            resultList.add(vo);
                        }
                    }
                } catch (Exception e) {
                    log.error("构建待审批任务VO失败，taskId: {}", taskActor.getTaskId(), e);
                }
            }

            log.info("成功构建待审批任务数量: {}", resultList.size());

            // 10. 根据instanceId去重，保留每个instanceId的第一个任务
            List<PendingApprovalTaskVO> deduplicatedList = deduplicateByInstanceId(resultList);
            log.info("根据instanceId去重后的任务数量: {}", deduplicatedList.size());

            // 11. 应用模糊匹配过滤
            List<PendingApprovalTaskVO> filteredList = applyFuzzyFilter(deduplicatedList, keyword);
            log.info("模糊匹配过滤后的任务数量: {}", filteredList.size());

            // 12. 应用排序
            filteredList = applySorting(filteredList, sortOrder);
            log.info("应用排序完成，排序方式: {}", sortOrder);

            // 13. 手动分页
            int start = (int) ((current - 1) * size);
            int end = Math.min(start + (int) size, filteredList.size());

            List<PendingApprovalTaskVO> pageData = filteredList.subList(start, end);

            Page<PendingApprovalTaskVO> page = new Page<>(current, size);
            page.setRecords(pageData);
            page.setTotal(filteredList.size());
            page.setCurrent(current);
            page.setSize(size);

            return page;

        } catch (Exception e) {
            log.error("获取用户 {} 待审批任务失败", userId, e);
            return new Page<>(current, size, 0);
        }
    }

    /**
     * 查找最顶级的父流程实例ID
     * 如果当前实例没有父实例，返回自身ID
     * 如果有父实例，递归查找直到找到最顶级的父实例
     */
    private Long findTopLevelParentInstanceId(Long instanceId) {
        try {
            // 先从当前实例表查询
            FlwInstance instance = flowLongEngine.queryService().getInstance(instanceId);
            if (instance != null) {
                if (instance.getParentInstanceId() == null) {
                    // 没有父实例，返回自身ID
                    return instanceId;
                } else {
                    // 有父实例，递归查找
                    return findTopLevelParentInstanceId(instance.getParentInstanceId());
                }
            }

            // 如果当前实例表没有，查询历史实例表
            FlwHisInstance hisInstance = flowLongEngine.queryService().getHistInstance(instanceId);
            if (hisInstance != null) {
                if (hisInstance.getParentInstanceId() == null) {
                    // 没有父实例，返回自身ID
                    return instanceId;
                } else {
                    // 有父实例，递归查找
                    return findTopLevelParentInstanceId(hisInstance.getParentInstanceId());
                }
            }

            // 如果都没找到，返回自身ID
            log.warn("未找到流程实例: {}, 返回自身ID", instanceId);
            return instanceId;

        } catch (Exception e) {
            log.error("查找最顶级父流程实例失败，instanceId: {}", instanceId, e);
            return instanceId;
        }
    }

    /**
     * 从流程引擎任务构建待审批任务VO对象
     */
    private PendingApprovalTaskVO buildPendingApprovalTaskVOFromFlwTask(
            com.aizuda.boot.modules.flw.entity.vo.PendingApprovalTaskVO flwTask,
            Map<Integer, Map<String, String>> contractFieldMap,
            Map<Integer, ContractEntity> contractMap,
            Map<Long, Long> topLevelInstanceMap,
            List<ContractEntity> approvalContracts) {

        try {
            // 获取最顶级实例ID
            Long topLevelInstanceId = topLevelInstanceMap.get(flwTask.getInstanceId());
            if (topLevelInstanceId == null) {
                log.warn("未找到最顶级实例ID，instanceId: {}", flwTask.getInstanceId());
                return null;
            }

            // 查找对应的合同
            ContractEntity contract = approvalContracts.stream()
                .filter(c -> c.getApprovalInstanceId().equals(topLevelInstanceId))
                .findFirst()
                .orElse(null);

            if (contract == null) {
                log.warn("未找到对应的合同，topLevelInstanceId: {}", topLevelInstanceId);
                return null;
            }

            // 获取合同字段值，允许字段值缺失
            Map<String, String> fieldValues = contractFieldMap.getOrDefault(contract.getId(), new HashMap<>());

            PendingApprovalTaskVO vo = new PendingApprovalTaskVO();

            // 基础信息 - 允许字段值为空
            vo.setContractId(contract.getId());
            vo.setContractName(fieldValues.getOrDefault(SystemFieldsEnum.CONTRACT_NAME.getCode(), "未知合同名称")); // 合同名称
            vo.setContractCode(fieldValues.getOrDefault(SystemFieldsEnum.CONTRACT_NUMBER.getCode(), "未知合同编号")); // 合同编号
            vo.setNodeName(flwTask.getTaskName()); // 当前节点名称

            // 新增字段
            vo.setInstanceId(flwTask.getInstanceId());
            vo.setInstanceState(flwTask.getInstanceState());

            // 创建时间
            if (flwTask.getCreateTime() != null) {
                vo.setCreateTime(flwTask.getCreateTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime());
            }

            // 查询流程类型
            String flowType = getFlowType(flwTask.getProcessId());
            vo.setFlowType(flowType);

            // 查询流程的processtype
            String processtype = getProcessType(flwTask.getProcessId());
            vo.setProcesstype(processtype);

            // 设置审批类型
            vo.setApprovalType("合同审批"); // 默认审批类型

            // 租户信息
            vo.setSysTenantKey(contract.getSysTenantKey());
            // ContractEntity中没有sysTenantName字段，暂时设置为空或者从其他地方获取
            vo.setSysTenantName(null);

            // 申请人信息 - 允许申请人信息缺失
            String applicantIdStr = fieldValues.get(SystemFieldsEnum.APPLY_PEOPLE.getCode()); // 申请人ID
            if (applicantIdStr != null && !applicantIdStr.trim().isEmpty()) {
                try {
                    Long applicantId = Long.valueOf(applicantIdStr.trim());
                    vo.setApplicantId(applicantId);

                    // 查询申请人详细信息
                    SysUser applicant = sysUserMapper.selectById(applicantId);
                    if (applicant != null) {
                        vo.setApplicantName(applicant.getRealName());
                        vo.setApplicantAvatar(applicant.getAvatar());

                        // 查询申请人部门
                        List<SysUserDepartment> userDepartments = sysUserDepartmentService.lambdaQuery()
                            .eq(SysUserDepartment::getUserId, applicantId)
                            .list();

                        if (!userDepartments.isEmpty()) {
                            Long departmentId = userDepartments.get(0).getDepartmentId();
                            SysDepartment department = sysDepartmentMapper.selectById(departmentId);
                            if (department != null) {
                                vo.setApplicantDepartment(department.getName());
                            }
                        }
                    } else {
                        vo.setApplicantName("未知申请人");
                    }
                } catch (NumberFormatException e) {
                    log.warn("申请人ID格式错误: {}", applicantIdStr);
                    vo.setApplicantName("申请人信息错误");
                }
            } else {
                // 没有申请人信息时的默认值
                vo.setApplicantName("未知申请人");
            }

            log.info("构建待审批任务VO完成，contractId: {}, taskId: {}, instanceId: {}",
                vo.getContractId(), vo.getTaskId(), vo.getInstanceId());

            return vo;

        } catch (Exception e) {
            log.error("构建待审批任务VO失败", e);
            return null;
        }
    }

    /**
     * 构建待审批任务VO对象
     */
    private PendingApprovalTaskVO buildPendingApprovalTaskVO(FlwTaskActor taskActor, 
            Map<Integer, Map<String, String>> contractFieldMap,
            List<ContractNegotiationInstanceEntity> negotiationInstances,
            Map<Integer, ContractEntity> contractMap) {
        
        log.info("开始构建VO，taskId: {}, instanceId: {}", taskActor.getTaskId(), taskActor.getInstanceId());
        
        try {
            // 查询流程实例信息
            FlwInstance flwInstance = flowLongEngine.queryService().getInstance(taskActor.getInstanceId());
            if (flwInstance == null) {
                log.warn("流程实例不存在: {}", taskActor.getInstanceId());
                return null;
            }
            
            // 注意：FlwInstance没有instanceState字段，审核中状态的过滤在历史实例中处理
            
            // 查询任务信息
            FlwTask flwTask = flowLongEngine.queryService().getTask(taskActor.getTaskId());
            if (flwTask == null) {
                log.warn("任务不存在: {}", taskActor.getTaskId());
                return null;
            }
            
            // 确定合同ID
            ContractInfo contractInfo = findContractInfo(taskActor.getInstanceId(), negotiationInstances, contractMap);
            if (contractInfo == null) {
                log.warn("无法找到对应的合同ID，instanceId: {}", taskActor.getInstanceId());
                return null;
            }
            
            // 获取合同字段值
            Map<String, String> fieldValues = contractFieldMap.get(contractInfo.getContractId());
            if (fieldValues == null) {
                log.warn("合同 {} 的字段值为空", contractInfo.getContractId());
                fieldValues = Map.of();
            }
            
            PendingApprovalTaskVO vo = new PendingApprovalTaskVO();
            
            // 基础信息
            vo.setContractId(contractInfo.getContractId());
            vo.setContractName(fieldValues.get(SystemFieldsEnum.CONTRACT_NAME.getCode())); // 合同名称
            vo.setContractCode(fieldValues.get(SystemFieldsEnum.CONTRACT_NUMBER.getCode())); // 合同编号
            vo.setApprovalType(contractInfo.getApprovalType()); // 审批类型
            vo.setNodeName(flwInstance.getCurrentNodeName());
            
            // 创建时间
            if (flwTask.getCreateTime() != null) {
                vo.setCreateTime(flwTask.getCreateTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime());
            }
            
            // 查询流程类型
            String flowType = getFlowType(flwInstance.getProcessId());
            vo.setFlowType(flowType);
            
            // 查询合同信息（用于获取租户信息）
            ContractEntity contract = contractMap.get(contractInfo.getContractId());
            if (contract != null) {
                String sysTenantKey = contract.getSysTenantKey();
                vo.setSysTenantKey(sysTenantKey);
                log.info("合同 {} 的租户键: {}", contractInfo.getContractId(), sysTenantKey);
                
                // 查询租户名称
                String sysTenantName;
                if (sysTenantKey != null) {
                    sysTenantName = getSysTenantName(sysTenantKey);
                } else {
                    // 租户键为空时的默认处理
                    sysTenantName = "默认租户";
                    log.warn("合同 {} 的租户键为空，使用默认租户名称", contractInfo.getContractId());
                }
                vo.setSysTenantName(sysTenantName);
                log.info("合同 {} 的租户名称: {}", contractInfo.getContractId(), sysTenantName);
            } else {
                log.warn("无法找到合同信息，contractId: {}", contractInfo.getContractId());
            }
            
            // 查询申请人信息
            String applicantIdStr = fieldValues.get(SystemFieldsEnum.APPLY_PEOPLE.getCode()); // 申请人
            if (applicantIdStr != null) {
                try {
                    Long applicantId = Long.valueOf(applicantIdStr);
                    vo.setApplicantId(applicantId);
                    
                    // 查询申请人头像和部门
                    SysUser applicant = sysUserMapper.selectById(applicantId);
                    if (applicant != null) {
                        vo.setApplicantAvatar(applicant.getAvatar());
                        vo.setApplicantName(applicant.getRealName());
                        
                        // 查询申请人的任意一个部门
                        String sysTenantKey = contract != null ? contract.getSysTenantKey() : null;
                        String applicantDepartment = getApplicantDepartment(applicantId, sysTenantKey);
                        vo.setApplicantDepartment(applicantDepartment);
                    }
                } catch (NumberFormatException e) {
                    log.warn("申请人ID格式错误: {}", applicantIdStr);
                }
            }
            
            log.info("构建VO完成，contractId: {}, approvalType: {}, sysTenantKey: {}, sysTenantName: {}", 
                vo.getContractId(), vo.getApprovalType(), vo.getSysTenantKey(), vo.getSysTenantName());
            
            return vo;
            
        } catch (Exception e) {
            log.error("构建待审批任务VO失败", e);
            return null;
        }
    }
    
    /**
     * 查找合同ID和审批类型
     */
    private ContractInfo findContractInfo(Long instanceId, List<ContractNegotiationInstanceEntity> negotiationInstances, 
            Map<Integer, ContractEntity> contractMap) {
        
        log.info("开始查找合同ID，instanceId: {}", instanceId);
        
        // 先从协商流程中查找
        for (ContractNegotiationInstanceEntity instance : negotiationInstances) {
            if (instanceId.equals(instance.getProcessInstanceId())) {
                log.info("从协商流程找到合同ID: {}，instanceId: {}，审批类型: 审核", instance.getContractId(), instanceId);
                return new ContractInfo(instance.getContractId(), "审核");
            }
        }
        
        // 再从审批流程中查找
        for (ContractEntity contract : contractMap.values()) {
            if (instanceId.equals(contract.getApprovalInstanceId())) {
                log.info("从审批流程找到合同ID: {}，instanceId: {}，审批类型: 审批", contract.getId(), instanceId);
                return new ContractInfo(contract.getId(), "审批");
            }
        }
        
        log.warn("未找到对应的合同ID，instanceId: {}", instanceId);
        return null;
    }
    
    /**
     * 获取流程类型
     */
    private String getFlowType(Long processId) {
        try {
            // 查询流程配置
            FlwProcessConfigure configure = flwProcessConfigureMapper.selectOne(
                Wrappers.<FlwProcessConfigure>lambdaQuery()
                    .eq(FlwProcessConfigure::getProcessId, processId)
            );
            
            if (configure != null) {
                // 查询流程分类
                FlwProcessCategory category = flwProcessCategoryMapper.selectById(configure.getCategoryId());
                if (category != null) {
                    return category.getName();
                }
            }
            
            return "未知类型";
        } catch (Exception e) {
            log.error("查询流程类型失败，processId: {}", processId, e);
            return "未知类型";
        }
    }

    /**
     * 获取流程类型（processtype字段）
     */
    private String getProcessType(Long processId) {
        try {
            // 查询流程定义
            FlwProcess process = flowLongEngine.processService().getProcessById(processId);
            if (process != null && process.getProcessType() != null) {
                String processTypeStr = process.getProcessType();

                // 使用枚举进行类型安全的处理
                try {
                    ProcessType processType = ProcessType.valueOf(processTypeStr);
                    return processType.name(); // 返回枚举名称
                } catch (IllegalArgumentException e) {
                    log.warn("未知的流程类型: {}, processId: {}, 使用默认值", processTypeStr, processId);
                    return ProcessType.business.name(); // 默认为业务流程
                }
            }

            return ProcessType.business.name(); // 默认为业务流程
        } catch (Exception e) {
            log.error("查询流程类型失败，processId: {}", processId, e);
            return ProcessType.business.name(); // 默认为业务流程
        }
    }

    /**
     * 获取系统租户名称
     */
    private String getSysTenantName(String sysTenantKey) {
        try {
            if (sysTenantKey == null) {
                log.info("sysTenantKey为null，无法查询租户名称");
                return null;
            }
            
            log.info("开始查询租户名称，sysTenantKey: {}", sysTenantKey);
            
            // 查询满足条件的部门
            List<SysDepartment> departments = sysDepartmentMapper.selectList(
                Wrappers.<SysDepartment>lambdaQuery()
                    .eq(SysDepartment::getSysTenantKey, sysTenantKey)
                    .and(wrapper -> wrapper
                        .eq(SysDepartment::getPid, 0L) // 顶级部门
                        .or()
                        .eq(SysDepartment::getIndependentFlag, 1) // 独立租户标识
                    )
                    .last("LIMIT 1")
            );
            
            log.info("查询到部门数量: {}，sysTenantKey: {}", departments.size(), sysTenantKey);
            
            if (!departments.isEmpty()) {
                String tenantName = departments.get(0).getName();
                log.info("找到租户名称: {}，sysTenantKey: {}", tenantName, sysTenantKey);
                return tenantName;
            }
            
            log.info("未找到匹配的部门，sysTenantKey: {}", sysTenantKey);
            return null;
        } catch (Exception e) {
            log.error("查询系统租户名称失败，sysTenantKey: {}", sysTenantKey, e);
            return null;
        }
    }
    
    /**
     * 获取申请人部门（优先返回主部门，没有主部门则返回任意一个部门）
     */
    private String getApplicantDepartment(Long userId, String sysTenantKey) {
        log.info("开始查询申请人部门，userId: {}, sysTenantKey: {}", userId, sysTenantKey);
        
        try {
            if (userId == null) {
                log.warn("userId为空，无法查询部门");
                return null;
            }
            
            // 先查找主部门
            log.info("查询主部门，userId: {}", userId);
            SysUserDepartment mainUserDept = sysUserDepartmentService.lambdaQuery()
                    .eq(SysUserDepartment::getUserId, userId)
                    .eq(SysUserDepartment::getIsMain, 1)
                    .one();
            
            log.info("主部门查询结果，userId: {}, mainUserDept: {}", userId, 
                    mainUserDept != null ? mainUserDept.getDepartmentId() : "null");
            
            if (mainUserDept != null) {
                // 直接获取主部门信息，不过滤租户
                log.info("查询主部门详情，userId: {}, departmentId: {}", userId, mainUserDept.getDepartmentId());
                SysDepartment mainDepartment = sysDepartmentMapper.selectOne(
                    Wrappers.<SysDepartment>lambdaQuery()
                        .eq(SysDepartment::getId, mainUserDept.getDepartmentId())
                        .eq(SysDepartment::getStatus, 1)
                );
                
                log.info("主部门详情查询结果，userId: {}, department: {}", userId, 
                        mainDepartment != null ? mainDepartment.getName() : "null");
                
                if (mainDepartment != null) {
                    log.info("找到申请人主部门，userId: {}, 部门名称: {}", userId, mainDepartment.getName());
                    return mainDepartment.getName();
                }
            }
            
            log.info("申请人没有主部门，查找任意一个部门，userId: {}", userId);
            
            // 如果没有主部门，查找任意一个部门
            SysUserDepartment anyUserDept = sysUserDepartmentService.lambdaQuery()
                    .eq(SysUserDepartment::getUserId, userId)
                    .last("LIMIT 1")
                    .one();
            
            log.info("任意部门查询结果，userId: {}, anyUserDept: {}", userId, 
                    anyUserDept != null ? anyUserDept.getDepartmentId() : "null");
            
            if (anyUserDept != null) {
                log.info("查询任意部门详情，userId: {}, departmentId: {}", userId, anyUserDept.getDepartmentId());
                SysDepartment department = sysDepartmentMapper.selectOne(
                    Wrappers.<SysDepartment>lambdaQuery()
                        .eq(SysDepartment::getId, anyUserDept.getDepartmentId())
                        .eq(SysDepartment::getStatus, 1)
                );
                
                log.info("任意部门详情查询结果，userId: {}, department: {}", userId, 
                        department != null ? department.getName() : "null");
                
                if (department != null) {
                    log.info("找到申请人其他部门，userId: {}, 部门名称: {}", userId, department.getName());
                    return department.getName();
                }
            }
            
            log.warn("申请人没有有效部门，userId: {}", userId);
            return null;
        } catch (Exception e) {
            log.error("查询申请人部门失败，userId: {}, sysTenantKey: {}", userId, sysTenantKey, e);
            return null;
        }
    }

    /**
     * 获取实例状态描述
     */
    private String getInstanceStateDescription(Integer instanceState) {
        if (instanceState == null) return "未知";
        switch (instanceState) {
            case -3: return "作废状态";
            case -2: return "已暂停状态";
            case -1: return "暂存待审";
            case 0: return "审批中";
            case 1: return "审批通过";
            case 2: return "审批拒绝";
            case 3: return "撤销审批";
            case 4: return "超时结束";
            case 5: return "强制终止";
            case 6: return "自动通过";
            case 7: return "自动拒绝";
            default: return "未知状态(" + instanceState + ")";
        }
    }

    @Override
    public Page<PendingApprovalTaskVO> getProcessedTasks(TaskCenterQueryDTO queryDTO, Long userId) {
        long current = queryDTO.getCurrent();
        long size = queryDTO.getSize();
        String keyword = queryDTO.getKeyword();
        String sortOrder = queryDTO.getSortOrder();

        log.info("获取用户 {} 的已处理任务列表，第 {} 页，每页 {} 条，关键词: {}，排序: {}", userId, current, size, keyword, sortOrder);

        try {
            // 获取当前用户的租户信息 - 修改逻辑：优先使用当前租户，如果为空则使用租户列表
            UserInfo currentUser = AuthUtil.getCurrentUser();
            String currentSysTenantKey = currentUser != null ? currentUser.getSysTenantKey() : null;
            List<String> userTenantKeys;

            if (currentSysTenantKey != null && !currentSysTenantKey.trim().isEmpty()) {
                // 如果当前用户有明确的sysTenantKey，只查询该租户下的数据
                userTenantKeys = List.of(currentSysTenantKey);
                log.info("已处理任务查询 - 使用当前租户过滤，租户键: {}", currentSysTenantKey);
            } else {
                // 如果sysTenantKey为null或空，使用原有逻辑（查询用户有权限的所有租户）
                userTenantKeys = AuthUtil.getUserTenantKeys();
                log.info("已处理任务查询 - 使用租户列表过滤，租户键列表: {}", userTenantKeys);
            }

            // 1. 直接查询 flw_his_task_actor 表，找到当前用户的所有已处理任务
            List<Map<String, Object>> historyTaskActors = contractMapper.selectHistoryTaskActors(userId.toString());
            log.info("【调试】从 flw_his_task_actor 表查询到用户 {} 的历史任务数量: {}", userId, historyTaskActors.size());

            // 打印前几条记录用于调试
            if (!historyTaskActors.isEmpty()) {
                log.info("【调试】历史任务示例（前3条）:");
                historyTaskActors.stream().limit(3).forEach(task -> {
                    log.info("【调试】  - taskId: {}, instanceId: {}, taskName: {}",
                        task.get("task_id"), task.get("instance_id"), task.get("task_name"));
                });
            }

            if (historyTaskActors.isEmpty()) {
                log.warn("【调试】用户 {} 在 flw_his_task_actor 表中没有已处理任务记录", userId);
                return new Page<>(current, size, 0);
            }

            // 2. 获取所有任务对应的实例ID
            List<Long> instanceIds = historyTaskActors.stream()
                .map(taskActor -> Long.valueOf(taskActor.get("instance_id").toString()))
                .distinct()
                .collect(Collectors.toList());

            log.info("涉及的流程实例ID数量: {}", instanceIds.size());

            // 3. 查询流程实例信息，过滤出 business 和 child 类型的流程
            List<Map<String, Object>> instancesWithProcess = contractMapper.selectInstancesWithProcessType(instanceIds);
            log.info("【调试】查询到的实例和流程类型数量: {}", instancesWithProcess.size());

            // 打印流程类型分布用于调试
            Map<String, Long> processTypeCount = instancesWithProcess.stream()
                .collect(Collectors.groupingBy(
                    instance -> String.valueOf(instance.get("process_type")),
                    Collectors.counting()
                ));
            log.info("【调试】流程类型分布: {}", processTypeCount);

            // 过滤出 business 和 child 类型的实例
            List<Map<String, Object>> validInstances = instancesWithProcess.stream()
                .filter(instance -> {
                    String processType = (String) instance.get("process_type");
                    boolean isValid = "business".equals(processType) || "child".equals(processType);
                    if (!isValid) {
                        log.debug("【调试】过滤掉流程类型: {}, instanceId: {}", processType, instance.get("instance_id"));
                    }
                    return isValid;
                })
                .collect(Collectors.toList());

            log.info("【调试】过滤后的有效实例数量（business/child类型）: {}", validInstances.size());

            if (validInstances.isEmpty()) {
                log.warn("【调试】没有找到 business 或 child 类型的流程实例，所有流程类型: {}", processTypeCount.keySet());
                return new Page<>(current, size, 0);
            }

            // 4. 提取有效的实例ID和对应的合同ID（通过business_key）
            List<Long> validInstanceIds = new ArrayList<>();
            List<Integer> contractIds = new ArrayList<>();

            for (Map<String, Object> instance : validInstances) {
                Long instanceId = Long.valueOf(instance.get("instance_id").toString());
                Object businessKeyObj = instance.get("business_key");

                if (businessKeyObj != null) {
                    try {
                        Integer contractId = Integer.valueOf(businessKeyObj.toString());
                        validInstanceIds.add(instanceId);
                        contractIds.add(contractId);
                        log.debug("【调试】有效的 business_key: {}, instanceId: {}", businessKeyObj, instanceId);
                    } catch (NumberFormatException e) {
                        log.warn("【调试】无效的 business_key: {}, instanceId: {}", businessKeyObj, instanceId);
                    }
                } else {
                    log.warn("【调试】business_key 为空, instanceId: {}", instanceId);
                }
            }

            log.info("【调试】有效的实例ID数量: {}, 对应的合同ID数量: {}", validInstanceIds.size(), contractIds.size());
            if (!contractIds.isEmpty()) {
                log.info("【调试】合同ID列表: {}", contractIds);
            }

            if (contractIds.isEmpty()) {
                log.warn("【调试】没有找到有效的合同ID，所有实例的 business_key 都为空或无效");
                return new Page<>(current, size, 0);
            }
            
            // 5. 查询合同信息并应用租户隔离
            LambdaQueryWrapper<ContractEntity> contractQueryWrapper = Wrappers.<ContractEntity>lambdaQuery()
                .in(ContractEntity::getId, contractIds);

            // 应用租户隔离
            if (userTenantKeys != null && !userTenantKeys.isEmpty()) {
                contractQueryWrapper.in(ContractEntity::getSysTenantKey, userTenantKeys);
                log.info("应用多租户隔离过滤，租户键列表: {}", userTenantKeys);
            } else if (userTenantKeys != null) {
                contractQueryWrapper.eq(ContractEntity::getSysTenantKey, "NO_PERMISSION");
                log.warn("用户没有任何租户权限");
            }

            List<ContractEntity> contracts = contractMapper.selectList(contractQueryWrapper);
            log.info("【调试】租户隔离后查询到合同数量: {}", contracts.size());

            if (contracts.isEmpty()) {
                log.warn("【调试】租户隔离后没有找到合法的合同记录");
                // 查询这些合同的实际租户信息用于调试
                List<ContractEntity> allContracts = contractMapper.selectList(
                    Wrappers.<ContractEntity>lambdaQuery()
                        .in(ContractEntity::getId, contractIds)
                        .select(ContractEntity::getId, ContractEntity::getSysTenantKey)
                );
                log.warn("【调试】原始合同的租户信息: {}", allContracts.stream()
                    .collect(Collectors.toMap(ContractEntity::getId,
                        c -> c.getSysTenantKey() == null ? "NULL" : c.getSysTenantKey())));
                log.warn("【调试】用户租户权限: {}", userTenantKeys);
                return new Page<>(current, size, 0);
            }

            // 6. 创建合同ID到合同对象的映射
            Map<Integer, ContractEntity> contractMap = contracts.stream()
                .collect(Collectors.toMap(ContractEntity::getId, contract -> contract));
            Set<Integer> validContractIds = contractMap.keySet();

            // 7. 过滤历史任务，只保留有效合同对应的任务
            List<Map<String, Object>> validHistoryTaskActors = historyTaskActors.stream()
                .filter(taskActor -> {
                    Long instanceId = Long.valueOf(taskActor.get("instance_id").toString());
                    return validInstanceIds.contains(instanceId);
                })
                .collect(Collectors.toList());

            log.info("过滤后的有效历史任务数量: {}", validHistoryTaskActors.size());
            
            // 8. 查询合同字段值
            // 使用字段代码动态获取字段ID
            List<Long> fieldIds = List.of(
                getFieldIdByCode(SystemFieldsEnum.CONTRACT_NAME.getCode()),
                getFieldIdByCode(SystemFieldsEnum.CONTRACT_NUMBER.getCode()),
                getFieldIdByCode(SystemFieldsEnum.APPLY_PEOPLE.getCode())
            ).stream().filter(Objects::nonNull).collect(Collectors.toList());
            
            List<ContractFieldValueEntity> fieldValues = contractFieldValueMapper.selectList(
                Wrappers.<ContractFieldValueEntity>lambdaQuery()
                    .in(ContractFieldValueEntity::getContractId, validContractIds)
                    .in(ContractFieldValueEntity::getFieldId, fieldIds)
            );

            // 按合同ID分组字段值，并将fieldId转换为fieldCode
            Map<Integer, Map<String, String>> contractFieldMap = fieldValues.stream()
                .collect(Collectors.groupingBy(
                    ContractFieldValueEntity::getContractId,
                    Collectors.toMap(
                        fieldValue -> {
                            // 将Long类型的fieldId转换为String类型的fieldCode
                            Long fieldId = fieldValue.getFieldId();
                            Long contractNameFieldId = getFieldIdByCode(SystemFieldsEnum.CONTRACT_NAME.getCode());
                            Long contractNumberFieldId = getFieldIdByCode(SystemFieldsEnum.CONTRACT_NUMBER.getCode());
                            Long applicantFieldId = getFieldIdByCode(SystemFieldsEnum.APPLY_PEOPLE.getCode());
                            
                            if (contractNameFieldId != null && fieldId.equals(contractNameFieldId)) {
                                return SystemFieldsEnum.CONTRACT_NAME.getCode();
                            } else if (contractNumberFieldId != null && fieldId.equals(contractNumberFieldId)) {
                                return SystemFieldsEnum.CONTRACT_NUMBER.getCode();
                            } else if (applicantFieldId != null && fieldId.equals(applicantFieldId)) {
                                return SystemFieldsEnum.APPLY_PEOPLE.getCode();
                            }
                            return fieldId.toString(); // 默认转换为字符串
                        },
                        ContractFieldValueEntity::getFieldValue
                    )
                ));

            // 9. 构建结果列表
            List<PendingApprovalTaskVO> resultList = new ArrayList<>();

            for (Map<String, Object> taskActor : validHistoryTaskActors) {
                try {
                    // 通过 business_key 找到对应的合同ID
                    Long instanceId = Long.valueOf(taskActor.get("instance_id").toString());
                    Integer contractId = findContractIdByInstanceId(instanceId, validInstances);
                    if (contractId != null && contractMap.containsKey(contractId)) {
                        PendingApprovalTaskVO vo = buildPendingApprovalTaskVOFromHistoryTaskActor(
                            taskActor, contractId, contractMap.get(contractId), contractFieldMap);
                        if (vo != null) {
                            resultList.add(vo);
                        }
                    }
                } catch (Exception e) {
                    log.error("构建已处理任务VO失败，taskActor: {}", taskActor, e);
                }
            }

            log.info("成功构建已处理任务数量: {}", resultList.size());

            // 10. 根据instanceId去重，保留每个instanceId的第一个任务
            List<PendingApprovalTaskVO> deduplicatedList = deduplicateByInstanceId(resultList);
            log.info("根据instanceId去重后的任务数量: {}", deduplicatedList.size());

            // 11. 应用模糊匹配过滤
            List<PendingApprovalTaskVO> filteredList = applyFuzzyFilter(deduplicatedList, keyword);
            log.info("模糊匹配过滤后的任务数量: {}", filteredList.size());

            // 12. 应用排序
            filteredList = applySorting(filteredList, sortOrder);
            log.info("应用排序完成，排序方式: {}", sortOrder);

            // 13. 手动分页
            int start = (int) ((current - 1) * size);
            int end = Math.min(start + (int) size, filteredList.size());

            List<PendingApprovalTaskVO> pageData = filteredList.subList(start, end);

            Page<PendingApprovalTaskVO> page = new Page<>(current, size);
            page.setRecords(pageData);
            page.setTotal(filteredList.size());
            page.setCurrent(current);
            page.setSize(size);

            return page;

        } catch (Exception e) {
            log.error("获取用户 {} 已处理任务失败", userId, e);
            return new Page<>(current, size, 0);
        }
    }

    /**
     * 构建已处理任务VO对象
     */
    private PendingApprovalTaskVO buildProcessedTaskVO(Long instanceId, Long taskId,
            Map<Integer, Map<String, String>> contractFieldMap,
            List<ContractNegotiationInstanceEntity> negotiationInstances,
            Map<Integer, ContractEntity> contractMap) {
        
        log.info("开始构建已处理任务VO，taskId: {}, instanceId: {}", taskId, instanceId);
        
        try {
            // 先尝试从当前实例表查询流程实例信息
            FlwInstance flwInstance = flowLongEngine.queryService().getInstance(instanceId);
            
            // 注意：FlwInstance没有instanceState字段，审核中状态的过滤在历史实例中处理
            
            // 如果当前实例表没有，再查询历史实例表
            if (flwInstance == null) {
                // 查询历史实例（优先查询历史表）
                Map<String, Object> instanceData = contractMapper.selectHistoryInstance(instanceId);
                if (instanceData == null) {
                    // 如果历史表没有，再查询当前表
                    instanceData = contractMapper.selectCurrentInstance(instanceId);
                }
                
                if (instanceData == null) {
                    log.warn("流程实例不存在（当前和历史表）: {}", instanceId);
                    return null;
                }
                Object instanceStateObj = instanceData.get("instance_state");
                if (instanceStateObj != null) {
                    Integer instanceState = Integer.valueOf(instanceStateObj.toString());
                    log.debug("历史流程实例状态: {} ({}), instanceId: {}",
                            instanceState, getInstanceStateDescription(instanceState), instanceId);
                }
                
                // 创建一个临时的FlwInstance对象用于后续处理
                flwInstance = new FlwInstance();
                flwInstance.setId(instanceId);
                flwInstance.setProcessId(Long.valueOf(instanceData.get("process_id").toString()));
                flwInstance.setCurrentNodeName((String) instanceData.get("current_node_name"));
            }
            
            // 查询历史任务信息
            Map<String, Object> taskData = contractMapper.selectHistoryTask(taskId);
            LocalDateTime createTime = null;
            
            if (taskData != null) {
                Object createTimeObj = taskData.get("create_time");
                if (createTimeObj != null) {
                    createTime = LocalDateTime.parse(createTimeObj.toString().replace(" ", "T"));
                }
            }
            
            // 确定合同ID
            ContractInfo contractInfo = findContractInfo(instanceId, negotiationInstances, contractMap);
            if (contractInfo == null) {
                log.warn("无法找到对应的合同ID，instanceId: {}", instanceId);
                return null;
            }
            
            // 获取合同字段值
            Map<String, String> fieldValues = contractFieldMap.get(contractInfo.getContractId());
            if (fieldValues == null) {
                log.warn("合同 {} 的字段值为空", contractInfo.getContractId());
                fieldValues = Map.of();
            }
            
            PendingApprovalTaskVO vo = new PendingApprovalTaskVO();
            
            // 基础信息
            vo.setContractId(contractInfo.getContractId());
            vo.setContractName(fieldValues.get(SystemFieldsEnum.CONTRACT_NAME.getCode())); // 合同名称
            vo.setContractCode(fieldValues.get(SystemFieldsEnum.CONTRACT_NUMBER.getCode())); // 合同编号
            vo.setApprovalType(contractInfo.getApprovalType()); // 审批类型
            vo.setNodeName(flwInstance.getCurrentNodeName());
            vo.setCreateTime(createTime);
            
            // 查询流程类型
            String flowType = getFlowType(flwInstance.getProcessId());
            vo.setFlowType(flowType);
            
            // 查询合同信息（用于获取租户信息）
            ContractEntity contract = contractMap.get(contractInfo.getContractId());
            if (contract != null) {
                String sysTenantKey = contract.getSysTenantKey();
                vo.setSysTenantKey(sysTenantKey);
                log.info("合同 {} 的租户键: {}", contractInfo.getContractId(), sysTenantKey);
                
                // 查询租户名称
                String sysTenantName;
                if (sysTenantKey != null) {
                    sysTenantName = getSysTenantName(sysTenantKey);
                } else {
                    // 租户键为空时的默认处理
                    sysTenantName = "默认租户";
                    log.warn("合同 {} 的租户键为空，使用默认租户名称", contractInfo.getContractId());
                }
                vo.setSysTenantName(sysTenantName);
                log.info("合同 {} 的租户名称: {}", contractInfo.getContractId(), sysTenantName);
            } else {
                log.warn("无法找到合同信息，contractId: {}", contractInfo.getContractId());
            }
            
            // 查询申请人信息
            String applicantIdStr = fieldValues.get(SystemFieldsEnum.APPLY_PEOPLE.getCode()); // 申请人
            if (applicantIdStr != null) {
                try {
                    Long applicantId = Long.valueOf(applicantIdStr);
                    vo.setApplicantId(applicantId);
                    
                    // 查询申请人头像、姓名和部门
                    SysUser applicant = sysUserMapper.selectById(applicantId);
                    if (applicant != null) {
                        vo.setApplicantAvatar(applicant.getAvatar());
                        vo.setApplicantName(applicant.getRealName());
                        
                        // 查询申请人的任意一个部门
                        String sysTenantKey = contract != null ? contract.getSysTenantKey() : null;
                        String applicantDepartment = getApplicantDepartment(applicantId, sysTenantKey);
                        vo.setApplicantDepartment(applicantDepartment);
                    }
                } catch (NumberFormatException e) {
                    log.warn("申请人ID格式错误: {}", applicantIdStr);
                }
            }
            
            log.info("构建已处理任务VO完成，contractId: {}, approvalType: {}, sysTenantKey: {}, sysTenantName: {}", 
                vo.getContractId(), vo.getApprovalType(), vo.getSysTenantKey(), vo.getSysTenantName());
            
            return vo;
            
        } catch (Exception e) {
            log.error("构建已处理任务VO失败", e);
            return null;
        }
    }

    @Override
    public Page<PendingApprovalTaskVO> getCcTasks(TaskCenterQueryDTO queryDTO, Long userId) {
        long current = queryDTO.getCurrent();
        long size = queryDTO.getSize();
        String keyword = queryDTO.getKeyword();
        String sortOrder = queryDTO.getSortOrder();

        log.info("查询抄送任务列表，用户ID: {}, 当前页: {}, 每页大小: {}，关键词: {}，排序: {}", userId, current, size, keyword, sortOrder);

        try {
            // 获取当前用户的租户信息 - 修改逻辑：优先使用当前租户，如果为空则使用租户列表
            UserInfo currentUser = AuthUtil.getCurrentUser();
            String currentSysTenantKey = currentUser != null ? currentUser.getSysTenantKey() : null;
            final List<String> userTenantKeys;

            if (currentSysTenantKey != null && !currentSysTenantKey.trim().isEmpty()) {
                // 如果当前用户有明确的sysTenantKey，只查询该租户下的数据
                userTenantKeys = List.of(currentSysTenantKey);
                log.info("抄送任务查询 - 使用当前租户过滤，租户键: {}", currentSysTenantKey);
            } else {
                // 如果sysTenantKey为null或空，使用原有逻辑（查询用户有权限的所有租户）
                userTenantKeys = AuthUtil.getUserTenantKeys();
                log.info("抄送任务查询 - 使用租户列表过滤，租户键列表: {}", userTenantKeys);
            }

            // 1. 调用mapper获取抄送任务
            ProcessTaskDTO processTaskDTO = new ProcessTaskDTO();
            processTaskDTO.setCreateId(userId.toString()); // 设置用户ID

            // 调用正确的服务接口，使用正确的分页方式
            Page<com.aizuda.boot.modules.flw.entity.vo.ProcessTaskVO> page = new Page<>(current, size);
            Page<com.aizuda.boot.modules.flw.entity.vo.ProcessTaskVO> flwPage =
                flowlongMapper.selectPageMyReceived(page, processTaskDTO);

            log.info("从流程引擎获取到 {} 条抄送任务", flwPage.getRecords().size());

            if (flwPage.getRecords().isEmpty()) {
                return new Page<>(current, size, 0);
            }

            // 2. 从流程引擎返回的任务中提取instanceId
            List<Long> instanceIds = flwPage.getRecords().stream()
                .map(com.aizuda.boot.modules.flw.entity.vo.ProcessTaskVO::getInstanceId)
                .distinct()
                .collect(Collectors.toList());

            log.info("涉及的流程实例ID数量: {}", instanceIds.size());

            // 3. 查找最顶级的父流程实例ID
            Map<Long, Long> topLevelInstanceMap = new HashMap<>();
            for (Long instanceId : instanceIds) {
                Long topLevelInstanceId = findTopLevelParentInstanceId(instanceId);
                topLevelInstanceMap.put(instanceId, topLevelInstanceId);
            }

            // 4. 收集所有最顶级的实例ID
            List<Long> topLevelInstanceIds = topLevelInstanceMap.values().stream()
                .distinct()
                .collect(Collectors.toList());

            log.info("最顶级流程实例ID数量: {}", topLevelInstanceIds.size());
            
            // 5. 使用最顶级实例ID查询合同（contract表中approval_instance_id）
            List<ContractEntity> approvalContracts = contractMapper.selectList(
                Wrappers.<ContractEntity>lambdaQuery()
                    .in(ContractEntity::getApprovalInstanceId, topLevelInstanceIds)
            );

            log.info("查询到审批流程合同数量: {}", approvalContracts.size());

            // 6. 收集所有合同ID
            List<Integer> contractIds = approvalContracts.stream()
                .map(ContractEntity::getId)
                .collect(Collectors.toList());

            if (contractIds.isEmpty()) {
                log.info("没有找到相关的合同记录");
                return new Page<>(current, size, 0);
            }

            log.info("找到相关合同数量: {}", contractIds.size());
            
            // 7. 查询所有相关合同的完整信息（包括租户信息）并应用租户隔离
            LambdaQueryWrapper<ContractEntity> contractQueryWrapper = Wrappers.<ContractEntity>lambdaQuery()
                .in(ContractEntity::getId, contractIds);

            // 应用租户隔离：只查询当前用户有权限的租户下的合同
            if (userTenantKeys != null && !userTenantKeys.isEmpty()) {
                contractQueryWrapper.in(ContractEntity::getSysTenantKey, userTenantKeys);
                log.info("应用多租户隔离过滤，租户键列表: {}", userTenantKeys);
            } else if (userTenantKeys != null) {
                // 空列表表示没有任何租户权限
                contractQueryWrapper.eq(ContractEntity::getSysTenantKey, "NO_PERMISSION");
                log.warn("用户没有任何租户权限");
            }

            List<ContractEntity> allContracts = contractMapper.selectList(contractQueryWrapper);
            log.info("租户隔离后查询到完整合同信息数量: {}", allContracts.size());

            if (allContracts.isEmpty()) {
                log.info("租户隔离后没有找到合法的合同记录");
                return new Page<>(current, size, 0);
            }

            // 按合同ID创建Map，便于后续查找
            Map<Integer, ContractEntity> contractMap = allContracts.stream()
                .collect(Collectors.toMap(ContractEntity::getId, contract -> contract));

            // 更新合同ID列表，只保留当前租户下的合同
            Set<Integer> validContractIds = contractMap.keySet();
            log.info("租户隔离后有效合同ID数量: {}", validContractIds.size());
            
            // 8. 查询合同字段值（合同名称、合同编号、申请人）
            // 使用字段代码动态获取字段ID
            List<Long> fieldIds = List.of(
                getFieldIdByCode(SystemFieldsEnum.CONTRACT_NAME.getCode()),
                getFieldIdByCode(SystemFieldsEnum.CONTRACT_NUMBER.getCode()),
                getFieldIdByCode(SystemFieldsEnum.APPLY_PEOPLE.getCode())
            ).stream().filter(Objects::nonNull).collect(Collectors.toList());
            
            List<ContractFieldValueEntity> fieldValues = contractFieldValueMapper.selectList(
                Wrappers.<ContractFieldValueEntity>lambdaQuery()
                    .in(ContractFieldValueEntity::getContractId, validContractIds)
                    .in(ContractFieldValueEntity::getFieldId, fieldIds)
            );

            // 按合同ID分组字段值，并将fieldId转换为fieldCode
            Map<Integer, Map<String, String>> contractFieldMap = fieldValues.stream()
                .collect(Collectors.groupingBy(
                    ContractFieldValueEntity::getContractId,
                    Collectors.toMap(
                        fieldValue -> {
                            // 将Long类型的fieldId转换为String类型的fieldCode
                            Long fieldId = fieldValue.getFieldId();
                            Long contractNameFieldId = getFieldIdByCode(SystemFieldsEnum.CONTRACT_NAME.getCode());
                            Long contractNumberFieldId = getFieldIdByCode(SystemFieldsEnum.CONTRACT_NUMBER.getCode());
                            Long applicantFieldId = getFieldIdByCode(SystemFieldsEnum.APPLY_PEOPLE.getCode());
                            
                            if (contractNameFieldId != null && fieldId.equals(contractNameFieldId)) {
                                return SystemFieldsEnum.CONTRACT_NAME.getCode();
                            } else if (contractNumberFieldId != null && fieldId.equals(contractNumberFieldId)) {
                                return SystemFieldsEnum.CONTRACT_NUMBER.getCode();
                            } else if (applicantFieldId != null && fieldId.equals(applicantFieldId)) {
                                return SystemFieldsEnum.APPLY_PEOPLE.getCode();
                            }
                            return fieldId.toString(); // 默认转换为字符串
                        },
                        ContractFieldValueEntity::getFieldValue
                    )
                ));

            // 9. 过滤流程引擎返回的任务，只保留租户隔离后有效的任务
            List<com.aizuda.boot.modules.flw.entity.vo.ProcessTaskVO> validFlwTasks = new ArrayList<>();
            for (com.aizuda.boot.modules.flw.entity.vo.ProcessTaskVO flwTask : flwPage.getRecords()) {
                Long topLevelInstanceId = topLevelInstanceMap.get(flwTask.getInstanceId());
                if (topLevelInstanceId != null) {
                    // 查找对应的合同
                    ContractEntity contract = approvalContracts.stream()
                        .filter(c -> c.getApprovalInstanceId().equals(topLevelInstanceId))
                        .findFirst()
                        .orElse(null);

                    if (contract != null && validContractIds.contains(contract.getId())) {
                        validFlwTasks.add(flwTask);
                    }
                }
            }

            log.info("租户隔离后有效抄送任务数量: {}", validFlwTasks.size());

            // 10. 构建结果列表
            List<PendingApprovalTaskVO> resultList = new ArrayList<>();

            // 处理每个有效的流程任务
            for (com.aizuda.boot.modules.flw.entity.vo.ProcessTaskVO flwTask : validFlwTasks) {
                try {
                    PendingApprovalTaskVO vo = buildPendingApprovalTaskVOFromFlwTask(flwTask, contractFieldMap,
                        contractMap, topLevelInstanceMap, approvalContracts);
                    if (vo != null) {
                        resultList.add(vo);
                    }
                } catch (Exception e) {
                    log.error("构建抄送任务VO失败，instanceId: {}", flwTask.getInstanceId(), e);
                }
            }

            log.info("成功构建抄送任务数量: {}", resultList.size());

            // 11. 根据instanceId去重，保留每个instanceId的第一个任务
            List<PendingApprovalTaskVO> deduplicatedList = deduplicateByInstanceId(resultList);
            log.info("根据instanceId去重后的任务数量: {}", deduplicatedList.size());

            // 12. 应用模糊匹配过滤
            List<PendingApprovalTaskVO> filteredList = applyFuzzyFilter(deduplicatedList, keyword);
            log.info("模糊匹配过滤后的任务数量: {}", filteredList.size());

            // 13. 应用排序
            filteredList = applySorting(filteredList, sortOrder);
            log.info("应用排序完成，排序方式: {}", sortOrder);

            // 14. 手动分页
            int total = filteredList.size();
            int startIndex = (int) ((current - 1) * size);
            int endIndex = Math.min(startIndex + (int) size, total);

            List<PendingApprovalTaskVO> pagedList = filteredList.subList(startIndex, endIndex);

            Page<PendingApprovalTaskVO> result = new Page<>(current, size, total);
            result.setRecords(pagedList);

            log.info("抄送任务分页结果 - 总数: {}, 当前页: {}, 每页大小: {}, 当前页记录数: {}",
                total, current, size, pagedList.size());

            return result;
            
        } catch (Exception e) {
            log.error("查询抄送任务失败", e);
            return new Page<>(current, size, 0);
        }
    }
    
    /**
     * 构建抄送任务VO
     */
    private PendingApprovalTaskVO buildCcTaskVO(Map<String, Object> record, 
                                                ContractInfo contractInfo,
                                                Map<Long, Map<String, Object>> instanceMap,
                                                Map<Long, Map<String, Object>> taskMap,
                                                Map<Long, ContractEntity> contractMap,
                                                Map<Long, Map<String, String>> contractFieldValues) {
        try {
            PendingApprovalTaskVO vo = new PendingApprovalTaskVO();
            
            // 基本信息
            vo.setContractId(contractInfo.getContractId());
            vo.setApprovalType(contractInfo.getApprovalType());
            
            // 获取合同字段值
            Long contractIdLong = Long.valueOf(contractInfo.getContractId());
            Map<String, String> fieldValues = contractFieldValues.get(contractIdLong);
            
            if (fieldValues != null) {
                vo.setContractName(fieldValues.get(SystemFieldsEnum.CONTRACT_NAME.getCode())); // 合同名称
                vo.setContractCode(fieldValues.get(SystemFieldsEnum.CONTRACT_NUMBER.getCode())); // 合同编号
            } else {
                log.warn("未找到合同字段值: contractId={}", contractInfo.getContractId());
            }
            
            // 获取实例信息
            Long instanceId = Long.valueOf(record.get("instance_id").toString());
            Map<String, Object> instanceInfo = instanceMap.get(instanceId);
            if (instanceInfo != null) {
                Long processId = Long.valueOf(instanceInfo.get("process_id").toString());
                String flowType = getFlowType(processId);
                vo.setFlowType(flowType);
            }
            
            // 获取任务信息
            Long taskId = Long.valueOf(record.get("task_id").toString());
            Map<String, Object> taskInfo = taskMap.get(taskId);
            if (taskInfo != null) {
                vo.setNodeName(taskInfo.get("task_name").toString());
            }
            
            // 设置创建时间（抄送时间）
            vo.setCreateTime(LocalDateTime.now()); // 这里可以根据实际需求调整
            
            // 查询合同信息（用于获取租户信息）
            ContractEntity contract = contractMap.get(Long.valueOf(contractInfo.getContractId()));
            if (contract != null) {
                String sysTenantKey = contract.getSysTenantKey();
                vo.setSysTenantKey(sysTenantKey);
                log.info("合同 {} 的租户键: {}", contractInfo.getContractId(), sysTenantKey);
                
                // 查询租户名称
                String sysTenantName;
                if (sysTenantKey != null) {
                    sysTenantName = getSysTenantName(sysTenantKey);
                } else {
                    sysTenantName = "默认租户";
                    log.warn("合同 {} 的租户键为空，使用默认租户名称", contractInfo.getContractId());
                }
                vo.setSysTenantName(sysTenantName);
            }
            
            // 查询申请人信息
            if (fieldValues != null) {
                String applicantIdStr = fieldValues.get(SystemFieldsEnum.APPLY_PEOPLE.getCode()); // 申请人
                if (applicantIdStr != null && !applicantIdStr.isEmpty()) {
                    try {
                        Long applicantId = Long.valueOf(applicantIdStr);
                        vo.setApplicantId(applicantId);
                        
                        // 查询申请人头像
                        SysUser applicant = sysUserMapper.selectById(applicantId);
                        if (applicant != null) {
                            vo.setApplicantAvatar(applicant.getAvatar());
                            vo.setApplicantName(applicant.getRealName());
                        }
                    
                    // 查询申请人部门
                    String applicantDepartment = getApplicantDepartment(applicantId, contract.getSysTenantKey());
                    vo.setApplicantDepartment(applicantDepartment);
                    
                    log.debug("申请人信息 - ID: {}, 部门: {}", applicantId, applicantDepartment);
                    } catch (NumberFormatException e) {
                        log.warn("申请人ID格式错误: {}", applicantIdStr);
                    }
                }
            }
            
            return vo;
            
        } catch (Exception e) {
            log.error("构建抄送任务VO失败", e);
            return null;
        }
    }
    
    /**
     * 应用模糊匹配过滤
     *
     * @param taskList 任务列表
     * @param keyword 关键词（可匹配合同名称或申请人姓名）
     * @return 过滤后的任务列表
     */
    private List<PendingApprovalTaskVO> applyFuzzyFilter(List<PendingApprovalTaskVO> taskList, String keyword) {
        if (taskList == null || taskList.isEmpty()) {
            return taskList;
        }
        
        // 如果没有关键词，直接返回原列表
        if (keyword == null || keyword.trim().isEmpty()) {
            return taskList;
        }
        
        log.info("开始应用关键词过滤，关键词: {}", keyword);
        
        String searchKeyword = keyword.trim().toLowerCase();
        
        return taskList.stream()
            .filter(task -> {
                // 检查合同名称匹配
                boolean matchesContractName = false;
                String taskContractName = task.getContractName();
                if (taskContractName != null) {
                    matchesContractName = taskContractName.toLowerCase().contains(searchKeyword);
                }
                
                // 检查申请人姓名匹配
                boolean matchesApplicantName = false;
                String applicantName = task.getApplicantName();
                if (applicantName != null) {
                    matchesApplicantName = applicantName.toLowerCase().contains(searchKeyword);
                }
                
                // 任意一个匹配即可
                return matchesContractName || matchesApplicantName;
            })
            .collect(Collectors.toList());
    }
    
    /**
     * 应用排序
     *
     * @param taskList 任务列表
     * @param sortOrder 排序方式（ASC/DESC）
     * @return 排序后的任务列表
     */
    private List<PendingApprovalTaskVO> applySorting(List<PendingApprovalTaskVO> taskList, String sortOrder) {
        if (taskList == null || taskList.isEmpty()) {
            return taskList;
        }
        
        // 默认为倒序
        if (sortOrder == null || sortOrder.trim().isEmpty()) {
            sortOrder = "DESC";
        }
        
        log.info("开始应用时间排序，排序方式: {}", sortOrder);
        
        if ("ASC".equalsIgnoreCase(sortOrder)) {
            // 正序：时间从早到晚
            return taskList.stream()
                .sorted((a, b) -> {
                    if (a.getCreateTime() == null && b.getCreateTime() == null) {
                        return 0;
                    }
                    if (a.getCreateTime() == null) {
                        return 1; // null排在后面
                    }
                    if (b.getCreateTime() == null) {
                        return -1; // null排在后面
                    }
                    return a.getCreateTime().compareTo(b.getCreateTime());
                })
                .collect(Collectors.toList());
        } else {
            // 倒序：时间从晚到早（默认）
            return taskList.stream()
                .sorted((a, b) -> {
                    if (a.getCreateTime() == null && b.getCreateTime() == null) {
                        return 0;
                    }
                    if (a.getCreateTime() == null) {
                        return 1; // null排在后面
                    }
                    if (b.getCreateTime() == null) {
                        return -1; // null排在后面
                    }
                    return b.getCreateTime().compareTo(a.getCreateTime());
                })
                .collect(Collectors.toList());
        }
    }
    


    /**
     * 从流程引擎已处理任务构建待审批任务VO对象
     */
    private PendingApprovalTaskVO buildProcessedTaskVOFromFlwTask(
            com.aizuda.boot.modules.flw.entity.vo.ProcessTaskVO flwTask,
            Map<Integer, Map<String, String>> contractFieldMap,
            Map<Integer, ContractEntity> contractMap,
            Map<Long, Long> topLevelInstanceMap,
            List<ContractEntity> approvalContracts) {

        try {
            // 获取最顶级实例ID
            Long topLevelInstanceId = topLevelInstanceMap.get(flwTask.getInstanceId());
            if (topLevelInstanceId == null) {
                log.warn("未找到最顶级实例ID，instanceId: {}", flwTask.getInstanceId());
                return null;
            }

            // 查找对应的合同
            ContractEntity contract = approvalContracts.stream()
                .filter(c -> c.getApprovalInstanceId().equals(topLevelInstanceId))
                .findFirst()
                .orElse(null);

            if (contract == null) {
                log.warn("未找到对应的合同，topLevelInstanceId: {}", topLevelInstanceId);
                return null;
            }

            // 获取合同字段值
            Map<String, String> fieldValues = contractFieldMap.get(contract.getId());
            if (fieldValues == null) {
                log.warn("合同 {} 的字段值为空", contract.getId());
                fieldValues = Map.of();
            }

            PendingApprovalTaskVO vo = new PendingApprovalTaskVO();

            // 基础信息
            vo.setContractId(contract.getId());
            vo.setContractName(fieldValues.get(SystemFieldsEnum.CONTRACT_NAME.getCode())); // 合同名称
            vo.setContractCode(fieldValues.get(SystemFieldsEnum.CONTRACT_NUMBER.getCode())); // 合同编号
            vo.setNodeName(flwTask.getCurrentNodeName()); // 当前节点名称

            // 新增字段 - 只添加instanceId，已处理任务不需要taskId和taskType
            vo.setInstanceId(flwTask.getInstanceId());
            vo.setInstanceState(flwTask.getInstanceState());

            // 创建时间
            if (flwTask.getCreateTime() != null) {
                vo.setCreateTime(flwTask.getCreateTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime());
            }

            // 查询流程类型
            String flowType = getFlowType(flwTask.getProcessId());
            vo.setFlowType(flowType);

            // 查询流程的processtype
            String processtype = getProcessType(flwTask.getProcessId());
            vo.setProcesstype(processtype);

            // 设置审批类型
            vo.setApprovalType("合同审批"); // 默认审批类型

            // 租户信息
            String sysTenantKey = contract.getSysTenantKey();
            vo.setSysTenantKey(sysTenantKey);
            if (sysTenantKey != null) {
                String sysTenantName = getSysTenantName(sysTenantKey);
                vo.setSysTenantName(sysTenantName);
            }

            // 申请人信息
            String applicantIdStr = fieldValues.get(SystemFieldsEnum.APPLY_PEOPLE.getCode()); // 申请人ID
            if (applicantIdStr != null && !applicantIdStr.trim().isEmpty()) {
                try {
                    Long applicantId = Long.valueOf(applicantIdStr.trim());
                    vo.setApplicantId(applicantId);

                    // 查询申请人详细信息
                    SysUser applicant = sysUserMapper.selectById(applicantId);
                    if (applicant != null) {
                        vo.setApplicantName(applicant.getRealName());
                        vo.setApplicantAvatar(applicant.getAvatar());

                        // 查询申请人部门
                        List<SysUserDepartment> userDepartments = sysUserDepartmentService.lambdaQuery()
                            .eq(SysUserDepartment::getUserId, applicantId)
                            .list();

                        if (!userDepartments.isEmpty()) {
                            Long departmentId = userDepartments.get(0).getDepartmentId();
                            SysDepartment department = sysDepartmentMapper.selectById(departmentId);
                            if (department != null) {
                                vo.setApplicantDepartment(department.getName());
                            }
                        }
                    }
                } catch (NumberFormatException e) {
                    log.warn("申请人ID格式错误: {}", applicantIdStr);
                }
            }

            log.info("构建已处理任务VO完成，contractId: {}, instanceId: {}",
                vo.getContractId(), vo.getInstanceId());

            return vo;

        } catch (Exception e) {
            log.error("构建已处理任务VO失败", e);
            return null;
        }
    }

    /**
     * 从流程引擎抄送任务构建待审批任务VO对象
     */
    private PendingApprovalTaskVO buildCcTaskVOFromFlwTask(
            com.aizuda.boot.modules.flw.entity.vo.ProcessTaskVO flwTask,
            Map<Integer, Map<String, String>> contractFieldMap,
            Map<Integer, ContractEntity> contractMap,
            Map<Long, Long> topLevelInstanceMap,
            List<ContractEntity> approvalContracts) {

        try {
            // 获取最顶级实例ID
            Long topLevelInstanceId = topLevelInstanceMap.get(flwTask.getInstanceId());
            if (topLevelInstanceId == null) {
                log.warn("未找到最顶级实例ID，instanceId: {}", flwTask.getInstanceId());
                return null;
            }

            // 查找对应的合同
            ContractEntity contract = approvalContracts.stream()
                .filter(c -> c.getApprovalInstanceId().equals(topLevelInstanceId))
                .findFirst()
                .orElse(null);

            if (contract == null) {
                log.warn("未找到对应的合同，topLevelInstanceId: {}", topLevelInstanceId);
                return null;
            }

            // 获取合同字段值
            Map<String, String> fieldValues = contractFieldMap.get(contract.getId());
            if (fieldValues == null) {
                log.warn("合同 {} 的字段值为空", contract.getId());
                fieldValues = Map.of();
            }

            PendingApprovalTaskVO vo = new PendingApprovalTaskVO();

            // 基础信息
            vo.setContractId(contract.getId());
            vo.setContractName(fieldValues.get(SystemFieldsEnum.CONTRACT_NAME.getCode())); // 合同名称
            vo.setContractCode(fieldValues.get(SystemFieldsEnum.CONTRACT_NUMBER.getCode())); // 合同编号
            vo.setNodeName(flwTask.getCurrentNodeName()); // 当前节点名称

            // 新增字段 - 只添加instanceId，抄送任务不需要taskId和taskType
            vo.setInstanceId(flwTask.getInstanceId());
            vo.setInstanceState(flwTask.getInstanceState());

            // 创建时间
            if (flwTask.getCreateTime() != null) {
                vo.setCreateTime(flwTask.getCreateTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime());
            }

            // 查询流程类型
            String flowType = getFlowType(flwTask.getProcessId());
            vo.setFlowType(flowType);

            // 查询流程的processtype
            String processtype = getProcessType(flwTask.getProcessId());
            vo.setProcesstype(processtype);

            // 设置审批类型
            vo.setApprovalType("合同审批"); // 默认审批类型

            // 租户信息
            vo.setSysTenantKey(contract.getSysTenantKey());
            // ContractEntity中没有sysTenantName字段，暂时设置为空
            vo.setSysTenantName(null);

            // 申请人信息
            String applicantIdStr = fieldValues.get(SystemFieldsEnum.APPLY_PEOPLE.getCode()); // 申请人ID
            if (applicantIdStr != null && !applicantIdStr.trim().isEmpty()) {
                try {
                    Long applicantId = Long.valueOf(applicantIdStr.trim());
                    vo.setApplicantId(applicantId);

                    // 查询申请人详细信息
                    SysUser applicant = sysUserMapper.selectById(applicantId);
                    if (applicant != null) {
                        vo.setApplicantName(applicant.getRealName());
                        vo.setApplicantAvatar(applicant.getAvatar());

                        // 查询申请人部门
                        List<SysUserDepartment> userDepartments = sysUserDepartmentService.lambdaQuery()
                            .eq(SysUserDepartment::getUserId, applicantId)
                            .list();

                        if (!userDepartments.isEmpty()) {
                            Long departmentId = userDepartments.get(0).getDepartmentId();
                            SysDepartment department = sysDepartmentMapper.selectById(departmentId);
                            if (department != null) {
                                vo.setApplicantDepartment(department.getName());
                            }
                        }
                    }
                } catch (NumberFormatException e) {
                    log.warn("申请人ID格式错误: {}", applicantIdStr);
                }
            }

            log.info("构建抄送任务VO完成，contractId: {}, instanceId: {}",
                vo.getContractId(), vo.getInstanceId());

            return vo;

        } catch (Exception e) {
            log.error("构建抄送任务VO失败", e);
            return null;
        }
    }

    @Override
    public TaskApprovalVO getSubProcessApprovalInfo(Long mainInstanceId, String subProcessNodeKey) {
        log.info("获取子流程审批信息，主实例ID: {}, 子流程节点: {}", mainInstanceId, subProcessNodeKey);

        try {
            // 1. 直接查询 flw_his_task 表找到子流程实例ID
            FlwHisTask hisTask = flwHisTaskMapper.selectOne(
                new LambdaQueryWrapper<FlwHisTask>()
                    .eq(FlwHisTask::getInstanceId, mainInstanceId)
                    .eq(FlwHisTask::getTaskKey, subProcessNodeKey)
                    .isNotNull(FlwHisTask::getCallInstanceId)
                    .last("LIMIT 1")
            );

            if (hisTask == null || hisTask.getCallInstanceId() == null) {
                log.warn("未找到对应的子流程实例，主实例ID: {}, 子流程节点: {}", mainInstanceId, subProcessNodeKey);
                throw new RuntimeException("未找到对应的子流程实例");
            }

            Long subProcessInstanceId = hisTask.getCallInstanceId();
            log.info("找到子流程实例ID: {}, 任务名称: {}", subProcessInstanceId, hisTask.getTaskName());

            // 2. 构造 ProcessInfoDTO 调用现有的 approvalInfo 方法
            ProcessInfoDTO processInfoDTO = new ProcessInfoDTO();
            processInfoDTO.setInstanceId(subProcessInstanceId);

            // 3. 调用现有的审批信息接口
            TaskApprovalVO result = flwProcessTaskService.approvalInfo(processInfoDTO);

            log.info("成功获取子流程审批信息，子流程实例ID: {}", subProcessInstanceId);
            return result;

        } catch (Exception e) {
            log.error("获取子流程审批信息失败，主实例ID: {}, 子流程节点: {}", mainInstanceId, subProcessNodeKey, e);
            throw new RuntimeException("获取子流程审批信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据实例ID查找对应的合同ID
     */
    private Integer findContractIdByInstanceId(Long instanceId, List<Map<String, Object>> validInstances) {
        for (Map<String, Object> instance : validInstances) {
            Long id = Long.valueOf(instance.get("instance_id").toString());
            if (id.equals(instanceId)) {
                Object businessKeyObj = instance.get("business_key");
                if (businessKeyObj != null) {
                    try {
                        return Integer.valueOf(businessKeyObj.toString());
                    } catch (NumberFormatException e) {
                        log.warn("无效的 business_key: {}, instanceId: {}", businessKeyObj, instanceId);
                    }
                }
            }
        }
        return null;
    }

    /**
     * 从 FlwTaskActor 构建待审批任务VO
     */
    private PendingApprovalTaskVO buildPendingApprovalTaskVOFromTaskActor(
            FlwTaskActor taskActor, Integer contractId, ContractEntity contract,
            Map<Integer, Map<String, String>> contractFieldMap) {

        try {
            PendingApprovalTaskVO vo = new PendingApprovalTaskVO();

            // 设置基本信息
            vo.setTaskId(taskActor.getTaskId());
            vo.setInstanceId(taskActor.getInstanceId());

            // 获取任务信息
            FlwTask task = flowLongEngine.queryService().getTask(taskActor.getTaskId());
            if (task != null) {
                if (task.getCreateTime() != null) {
                    vo.setCreateTime(task.getCreateTime().toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime());
                }
                vo.setTaskType(task.getTaskType());
                vo.setNodeName(task.getTaskName()); // 设置当前节点名称
            }

            // 获取实例信息
            FlwInstance instance = flowLongEngine.queryService().getInstance(taskActor.getInstanceId());
            if (instance != null) {
                vo.setInstanceId(instance.getId());
                vo.setInstanceState(0); // 活动实例状态固定为0（审批中）

                // 获取流程信息
                FlwProcess process = flowLongEngine.processService().getProcessById(instance.getProcessId());
                if (process != null) {
                    vo.setProcesstype(process.getProcessType());

                    // 查询流程类型
                    String flowType = getFlowType(process.getId());
                    vo.setFlowType(flowType);
                }
            }

            // 设置合同相关信息
            if (contract != null) {
                vo.setContractId(contractId);

                // 获取合同字段值
                Map<String, String> fieldValues = contractFieldMap.get(contractId);
                if (fieldValues != null) {
                    vo.setContractName(fieldValues.get(SystemFieldsEnum.CONTRACT_NAME.getCode())); // 合同名称
                    vo.setContractCode(fieldValues.get(SystemFieldsEnum.CONTRACT_NUMBER.getCode())); // 合同编号
                }

                // 设置租户信息
                String sysTenantKey = contract.getSysTenantKey();
                vo.setSysTenantKey(sysTenantKey);

                if (sysTenantKey != null) {
                    String sysTenantName = getSysTenantName(sysTenantKey);
                    vo.setSysTenantName(sysTenantName);
                }

                // 设置申请人信息
                if (instance != null && instance.getCreateId() != null) {
                    try {
                        SysUser applicant = sysUserMapper.selectById(Long.valueOf(instance.getCreateId()));
                        if (applicant != null) {
                            vo.setApplicantId(applicant.getId());
                            vo.setApplicantName(applicant.getNickName());
                            vo.setApplicantAvatar(applicant.getAvatar());

                            // 查询申请人部门
                            String departmentName = getApplicantDepartment(applicant.getId(), sysTenantKey);
                            vo.setApplicantDepartment(departmentName);
                        } else {
                            vo.setApplicantName("未知申请人");
                        }
                    } catch (Exception e) {
                        log.warn("获取申请人信息失败，createId: {}", instance.getCreateId(), e);
                        vo.setApplicantName("未知申请人");
                    }
                } else {
                    vo.setApplicantName("未知申请人");
                }
            }

            return vo;

        } catch (Exception e) {
            log.error("构建待审批任务VO失败，taskId: {}, contractId: {}", taskActor.getTaskId(), contractId, e);
            return null;
        }
    }

    /**
     * 从历史任务参与者构建已处理任务VO
     */
    private PendingApprovalTaskVO buildPendingApprovalTaskVOFromHistoryTaskActor(
            Map<String, Object> taskActor, Integer contractId, ContractEntity contract,
            Map<Integer, Map<String, String>> contractFieldMap) {

        try {
            PendingApprovalTaskVO vo = new PendingApprovalTaskVO();

            // 设置基本信息
            vo.setInstanceId(Long.valueOf(taskActor.get("instance_id").toString()));

            // 设置任务信息
            Object createTimeObj = taskActor.get("create_time");
            if (createTimeObj != null) {
                if (createTimeObj instanceof LocalDateTime) {
                    vo.setCreateTime((LocalDateTime) createTimeObj);
                } else if (createTimeObj instanceof Date) {
                    vo.setCreateTime(((Date) createTimeObj).toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime());
                }
            }

            // 获取历史实例信息
            try {
                FlwHisInstance hisInstance = flowLongEngine.queryService().getHistInstance(vo.getInstanceId());
                if (hisInstance != null) {
                    vo.setInstanceId(hisInstance.getId());
                    vo.setInstanceState(hisInstance.getInstanceState());
            
                    // 获取流程信息
                    FlwProcess process = flowLongEngine.processService().getProcessById(hisInstance.getProcessId());
                    if (process != null) {
                        vo.setProcesstype(process.getProcessType());
                    }
                }
            } catch (Exception e) {
                log.debug("获取历史实例信息失败，instanceId: {}", vo.getInstanceId(), e);
            }

            // 获取任务名称（节点名称）
            try {
                Object taskNameObj = taskActor.get("task_name");
                if (taskNameObj != null) {
                    vo.setNodeName(taskNameObj.toString());
                }
            } catch (Exception e) {
                log.debug("获取任务名称失败", e);
            }

            // 设置合同相关信息
            if (contract != null) {
                vo.setContractId(contractId);

                // 获取合同字段值
                Map<String, String> fieldValues = contractFieldMap.get(contractId);
                if (fieldValues != null) {
                    vo.setContractName(fieldValues.get(SystemFieldsEnum.CONTRACT_NAME.getCode())); // 合同名称
                    vo.setContractCode(fieldValues.get(SystemFieldsEnum.CONTRACT_NUMBER.getCode())); // 合同编号
                }

                // 设置审批类型
                vo.setApprovalType("合同审批"); // 默认审批类型

                // 设置租户信息
                String sysTenantKey = contract.getSysTenantKey();
                vo.setSysTenantKey(sysTenantKey);

                if (sysTenantKey != null) {
                    String sysTenantName = getSysTenantName(sysTenantKey);
                    vo.setSysTenantName(sysTenantName);
                }
            }

            // 设置流程类型
            try {
                FlwHisInstance hisInstance = flowLongEngine.queryService().getHistInstance(vo.getInstanceId());
                if (hisInstance != null) {
                    FlwProcess process = flowLongEngine.processService().getProcessById(hisInstance.getProcessId());
                    if (process != null) {
                        String flowType = getFlowType(process.getId());
                        vo.setFlowType(flowType);
                    }

                    // 设置申请人信息
                    if (hisInstance.getCreateId() != null) {
                        try {
                            SysUser applicant = sysUserMapper.selectById(Long.valueOf(hisInstance.getCreateId()));
                            if (applicant != null) {
                                vo.setApplicantId(applicant.getId());
                                vo.setApplicantName(applicant.getRealName());
                                vo.setApplicantAvatar(applicant.getAvatar());

                                // 查询申请人部门
                                String departmentName = getApplicantDepartment(applicant.getId(),
                                    contract != null ? contract.getSysTenantKey() : null);
                                vo.setApplicantDepartment(departmentName);
                            }
                        } catch (Exception e) {
                            log.debug("获取申请人信息失败", e);
                        }
                    }
                }
            } catch (Exception e) {
                log.debug("获取流程和申请人信息失败", e);
            }

            return vo;

        } catch (Exception e) {
            log.error("构建已处理任务VO失败，taskActor: {}, contractId: {}", taskActor, contractId, e);
            return null;
        }
    }





    /**
     * 从 FlwTask 构建待审批任务VO（用于抄送任务）
     */
    private PendingApprovalTaskVO buildPendingApprovalTaskVOFromFlwTask(
            com.aizuda.boot.modules.flw.entity.vo.ProcessTaskVO flwTask,
            Map<Integer, Map<String, String>> contractFieldMap,
            Map<Integer, ContractEntity> contractMap,
            Map<Long, Long> topLevelInstanceMap,
            List<ContractEntity> approvalContracts) {

        try {
            PendingApprovalTaskVO vo = new PendingApprovalTaskVO();

            // 设置基本信息
            vo.setInstanceId(flwTask.getInstanceId());
            vo.setProcesstype(flwTask.getProcessType());
            vo.setInstanceState(flwTask.getInstanceState());

            // 设置创建时间
            if (flwTask.getCreateTime() != null) {
                vo.setCreateTime(flwTask.getCreateTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime());
            }

            // 设置当前节点名称
            vo.setNodeName(flwTask.getCurrentNodeName());

            // 尝试获取合同相关信息
            try {
                // 通过实例ID查找对应的合同
                Long topLevelInstanceId = topLevelInstanceMap.get(flwTask.getInstanceId());
                if (topLevelInstanceId != null) {
                    // 查找对应的合同
                    ContractEntity matchedContract = approvalContracts.stream()
                        .filter(contract -> {
                            try {
                                // 使用 approvalInstanceId 字段来匹配
                                return contract.getApprovalInstanceId() != null &&
                                       contract.getApprovalInstanceId().equals(topLevelInstanceId);
                            } catch (Exception e) {
                                return false;
                            }
                        })
                        .findFirst()
                        .orElse(null);

                    if (matchedContract != null) {
                        vo.setContractId(matchedContract.getId());

                        // 获取合同字段值
                        Map<String, String> fieldValues = contractFieldMap.get(matchedContract.getId());
                        if (fieldValues != null) {
                            vo.setContractName(fieldValues.get(SystemFieldsEnum.CONTRACT_NAME.getCode())); // 合同名称
                            vo.setContractCode(fieldValues.get(SystemFieldsEnum.CONTRACT_NUMBER.getCode())); // 合同编号
                        }

                        // 设置审批类型
                        vo.setApprovalType("合同审批"); // 默认审批类型

                        // 设置租户信息
                        String sysTenantKey = matchedContract.getSysTenantKey();
                        vo.setSysTenantKey(sysTenantKey);

                        if (sysTenantKey != null) {
                            String sysTenantName = getSysTenantName(sysTenantKey);
                            vo.setSysTenantName(sysTenantName);
                        }

                        // 设置流程类型
                        try {
                            FlwProcess process = flowLongEngine.processService().getProcessById(flwTask.getProcessId());
                            if (process != null) {
                                String flowType = getFlowType(process.getId());
                                vo.setFlowType(flowType);
                            }
                        } catch (Exception e) {
                            log.debug("获取流程类型失败", e);
                        }

                        // 设置申请人信息
                        try {
                            if (flwTask.getCreateId() != null) {
                                SysUser applicant = sysUserMapper.selectById(Long.valueOf(flwTask.getCreateId()));
                                if (applicant != null) {
                                    vo.setApplicantId(applicant.getId());
                                    vo.setApplicantName(applicant.getRealName());
                                    vo.setApplicantAvatar(applicant.getAvatar());

                                    // 查询申请人部门
                                    String departmentName = getApplicantDepartment(applicant.getId(), sysTenantKey);
                                    vo.setApplicantDepartment(departmentName);
                                }
                            }
                        } catch (Exception e) {
                            log.debug("获取申请人信息失败", e);
                        }
                    }
                }
            } catch (Exception e) {
                log.debug("获取抄送任务合同信息失败，instanceId: {}", flwTask.getInstanceId(), e);
            }

            return vo;

        } catch (Exception e) {
            log.error("构建抄送任务VO失败，instanceId: {}", flwTask.getInstanceId(), e);
            return null;
        }
    }

    /**
     * 根据instanceId去重，保留每个instanceId的第一个任务
     * 
     * @param taskList 原始任务列表
     * @return 去重后的任务列表
     */
    private List<PendingApprovalTaskVO> deduplicateByInstanceId(List<PendingApprovalTaskVO> taskList) {
        if (taskList == null || taskList.isEmpty()) {
            return taskList;
        }

        // 使用LinkedHashMap保持插入顺序，保留每个instanceId的第一个任务
        Map<Long, PendingApprovalTaskVO> deduplicatedMap = new LinkedHashMap<>();
        List<PendingApprovalTaskVO> nullInstanceIdTasks = new ArrayList<>();
        
        for (PendingApprovalTaskVO task : taskList) {
            if (task.getInstanceId() != null) {
                // 只有当instanceId不存在时才添加，这样保留第一个出现的任务
                deduplicatedMap.putIfAbsent(task.getInstanceId(), task);
            } else {
                // 如果instanceId为null，保留所有这样的任务（不去重）
                nullInstanceIdTasks.add(task);
                log.debug("保留instanceId为null的任务: contractId={}, taskId={}", 
                    task.getContractId(), task.getTaskId());
            }
        }
        
        // 合并结果：先是去重后的有instanceId的任务，然后是所有instanceId为null的任务
        List<PendingApprovalTaskVO> result = new ArrayList<>(deduplicatedMap.values());
        result.addAll(nullInstanceIdTasks);
        
                log.info("instanceId去重完成: 原始数量={}, 去重后数量={}, 去除重复数量={}, instanceId为null的任务数={}",
            taskList.size(), result.size(), taskList.size() - result.size(), nullInstanceIdTasks.size());
        
        return result;
    }

    // ==================== 性能优化方法 ====================
    
    /**
     * 优化的待审批任务查询 - 使用单次SQL查询替代多次数据库访问和递归查询
     */
    @Override
    public Page<PendingApprovalTaskVO> getPendingApprovalTasksOptimized(TaskCenterQueryDTO queryDTO, Long userId) {
        long current = queryDTO.getCurrent();
        long size = queryDTO.getSize();
        String keyword = queryDTO.getKeyword();
        String sortOrder = queryDTO.getSortOrder();

        log.info("【优化版本】获取用户 {} 的待审批任务列表，第 {} 页，每页 {} 条，关键词: {}，排序: {}", userId, current, size, keyword, sortOrder);

        try {
            // 获取租户权限
            UserInfo currentUser = AuthUtil.getCurrentUser();
            String currentSysTenantKey = currentUser != null ? currentUser.getSysTenantKey() : null;
            List<String> userTenantKeys;

            if (currentSysTenantKey != null && !currentSysTenantKey.trim().isEmpty()) {
                userTenantKeys = List.of(currentSysTenantKey);
                log.info("【优化版本】待审批任务查询 - 使用当前租户过滤，租户键: {}", currentSysTenantKey);
            } else {
                userTenantKeys = AuthUtil.getUserTenantKeys();
                log.info("【优化版本】待审批任务查询 - 使用租户列表过滤，租户键列表: {}", userTenantKeys);
            }

            // 单次SQL查询获取所有数据
            List<Map<String, Object>> results = contractMapper.selectPendingTasksOptimized(userId.toString(), userTenantKeys);
            log.info("【优化版本】单次SQL查询返回 {} 条记录", results.size());

            // 转换为VO对象
            List<PendingApprovalTaskVO> resultList = results.stream()
                .map(this::buildTaskVOFromMap)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

            log.info("【优化版本】成功构建待审批任务数量: {}", resultList.size());

            // 根据instanceId去重，保留每个instanceId的第一个任务
            List<PendingApprovalTaskVO> deduplicatedList = deduplicateByInstanceId(resultList);
            log.info("【优化版本】根据instanceId去重后的任务数量: {}", deduplicatedList.size());

            // 应用模糊匹配过滤
            List<PendingApprovalTaskVO> filteredList = applyFuzzyFilter(deduplicatedList, keyword);
            log.info("【优化版本】模糊匹配过滤后的任务数量: {}", filteredList.size());

            // 应用排序
            filteredList = applySorting(filteredList, sortOrder);
            log.info("【优化版本】应用排序完成，排序方式: {}", sortOrder);

            // 手动分页
            int start = (int) ((current - 1) * size);
            int end = Math.min(start + (int) size, filteredList.size());

            List<PendingApprovalTaskVO> pageData = filteredList.subList(start, end);

            Page<PendingApprovalTaskVO> page = new Page<>(current, size);
            page.setRecords(pageData);
            page.setTotal(filteredList.size());
            page.setCurrent(current);
            page.setSize(size);

            return page;

        } catch (Exception e) {
            log.error("【优化版本】获取用户 {} 待审批任务失败", userId, e);
            return new Page<>(current, size, 0);
        }
    }

    /**
     * 优化的已处理任务查询 - 使用单次SQL查询替代多次数据库访问
     */
    @Override
    public Page<PendingApprovalTaskVO> getProcessedTasksOptimized(TaskCenterQueryDTO queryDTO, Long userId) {
        long current = queryDTO.getCurrent();
        long size = queryDTO.getSize();
        String keyword = queryDTO.getKeyword();
        String sortOrder = queryDTO.getSortOrder();

        log.info("【优化版本】获取用户 {} 的已处理任务列表，第 {} 页，每页 {} 条，关键词: {}，排序: {}", userId, current, size, keyword, sortOrder);

        try {
            // 获取租户权限
            UserInfo currentUser = AuthUtil.getCurrentUser();
            String currentSysTenantKey = currentUser != null ? currentUser.getSysTenantKey() : null;
            List<String> userTenantKeys;

            if (currentSysTenantKey != null && !currentSysTenantKey.trim().isEmpty()) {
                userTenantKeys = List.of(currentSysTenantKey);
                log.info("【优化版本】已处理任务查询 - 使用当前租户过滤，租户键: {}", currentSysTenantKey);
            } else {
                userTenantKeys = AuthUtil.getUserTenantKeys();
                log.info("【优化版本】已处理任务查询 - 使用租户列表过滤，租户键列表: {}", userTenantKeys);
            }

            // 单次SQL查询获取所有数据
            List<Map<String, Object>> results = contractMapper.selectProcessedTasksOptimized(userId.toString(), userTenantKeys);
            log.info("【优化版本】单次SQL查询返回 {} 条记录", results.size());

            // 转换为VO对象（对于已处理任务，使用finish_time作为排序时间）
            List<PendingApprovalTaskVO> resultList = results.stream()
                .map(record -> buildProcessedTaskVOFromMap(record))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

            log.info("【优化版本】成功构建已处理任务数量: {}", resultList.size());

            // 根据instanceId去重，保留每个instanceId的第一个任务
            List<PendingApprovalTaskVO> deduplicatedList = deduplicateByInstanceId(resultList);
            log.info("【优化版本】根据instanceId去重后的任务数量: {}", deduplicatedList.size());

            // 应用模糊匹配过滤
            List<PendingApprovalTaskVO> filteredList = applyFuzzyFilter(deduplicatedList, keyword);
            log.info("【优化版本】模糊匹配过滤后的任务数量: {}", filteredList.size());

            // 应用排序
            filteredList = applySorting(filteredList, sortOrder);
            log.info("【优化版本】应用排序完成，排序方式: {}", sortOrder);

            // 手动分页
            int start = (int) ((current - 1) * size);
            int end = Math.min(start + (int) size, filteredList.size());

            List<PendingApprovalTaskVO> pageData = filteredList.subList(start, end);

            Page<PendingApprovalTaskVO> page = new Page<>(current, size);
            page.setRecords(pageData);
            page.setTotal(filteredList.size());
            page.setCurrent(current);
            page.setSize(size);

            return page;

        } catch (Exception e) {
            log.error("【优化版本】获取用户 {} 已处理任务失败", userId, e);
            return new Page<>(current, size, 0);
        }
    }

    /**
     * 优化的抄送任务查询 - 使用单次SQL查询替代流程引擎API调用和多次数据库访问
     */
    @Override
    public Page<PendingApprovalTaskVO> getCcTasksOptimized(TaskCenterQueryDTO queryDTO, Long userId) {
        long current = queryDTO.getCurrent();
        long size = queryDTO.getSize();
        String keyword = queryDTO.getKeyword();
        String sortOrder = queryDTO.getSortOrder();

        log.info("【优化版本】查询抄送任务列表，用户ID: {}, 当前页: {}, 每页大小: {}，关键词: {}，排序: {}", userId, current, size, keyword, sortOrder);

        try {
            // 获取租户权限
            UserInfo currentUser = AuthUtil.getCurrentUser();
            String currentSysTenantKey = currentUser != null ? currentUser.getSysTenantKey() : null;
            List<String> userTenantKeys;

            if (currentSysTenantKey != null && !currentSysTenantKey.trim().isEmpty()) {
                userTenantKeys = List.of(currentSysTenantKey);
                log.info("【优化版本】抄送任务查询 - 使用当前租户过滤，租户键: {}", currentSysTenantKey);
            } else {
                userTenantKeys = AuthUtil.getUserTenantKeys();
                log.info("【优化版本】抄送任务查询 - 使用租户列表过滤，租户键列表: {}", userTenantKeys);
            }

            // 单次SQL查询获取所有数据
            List<Map<String, Object>> results = contractMapper.selectCcTasksOptimized(userId.toString(), userTenantKeys);
            log.info("【优化版本】单次SQL查询返回 {} 条记录", results.size());

            // 转换为VO对象
            List<PendingApprovalTaskVO> resultList = results.stream()
                .map(this::buildCcTaskVOFromMap)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

            log.info("【优化版本】成功构建抄送任务数量: {}", resultList.size());

            // 根据instanceId去重，保留每个instanceId的第一个任务
            List<PendingApprovalTaskVO> deduplicatedList = deduplicateByInstanceId(resultList);
            log.info("【优化版本】根据instanceId去重后的任务数量: {}", deduplicatedList.size());

            // 应用模糊匹配过滤
            List<PendingApprovalTaskVO> filteredList = applyFuzzyFilter(deduplicatedList, keyword);
            log.info("【优化版本】模糊匹配过滤后的任务数量: {}", filteredList.size());

            // 应用排序
            filteredList = applySorting(filteredList, sortOrder);
            log.info("【优化版本】应用排序完成，排序方式: {}", sortOrder);

            // 手动分页
            int start = (int) ((current - 1) * size);
            int end = Math.min(start + (int) size, filteredList.size());

            List<PendingApprovalTaskVO> pageData = filteredList.subList(start, end);

            Page<PendingApprovalTaskVO> page = new Page<>(current, size);
            page.setRecords(pageData);
            page.setTotal(filteredList.size());
            page.setCurrent(current);
            page.setSize(size);

            return page;

        } catch (Exception e) {
            log.error("【优化版本】查询抄送任务失败", e);
            return new Page<>(current, size, 0);
        }
    }

    /**
     * 从SQL查询结果Map构建任务VO - 通用方法（SQL已包含所有必要信息，避免循环查询）
     */
    private PendingApprovalTaskVO buildTaskVOFromMap(Map<String, Object> record) {
        try {
            PendingApprovalTaskVO vo = new PendingApprovalTaskVO();
            
            // 基础信息
            vo.setContractId(((Number) record.get("contract_id")).intValue());
            vo.setContractName((String) record.get("contract_name"));
            vo.setContractCode((String) record.get("contract_code"));
            vo.setNodeName((String) record.get("current_node_name"));
            
            // 任务信息
            vo.setInstanceId(((Number) record.get("instance_id")).longValue());
            vo.setTaskId(((Number) record.get("task_id")).longValue());
            vo.setTaskType(1); // 任务类型 (approval = 1)
            
            // 时间信息 - 优先使用apply_time，如果没有则使用create_time
            Object applyTimeObj = record.get("apply_time");
            Object createTimeObj = record.get("create_time");
            
            boolean timeSet = false;
            
            // 处理apply_time字段（用于pending和processed）
            if (applyTimeObj != null) {
                if (applyTimeObj instanceof java.sql.Timestamp) {
                    vo.setCreateTime(((java.sql.Timestamp) applyTimeObj).toLocalDateTime());
                    timeSet = true;
                } else if (applyTimeObj instanceof java.time.LocalDateTime) {
                    vo.setCreateTime((java.time.LocalDateTime) applyTimeObj);
                    timeSet = true;
                } else if (applyTimeObj instanceof java.util.Date) {
                    vo.setCreateTime(((java.util.Date) applyTimeObj).toInstant()
                        .atZone(java.time.ZoneId.systemDefault()).toLocalDateTime());
                    timeSet = true;
                } else {
                    log.debug("apply_time字段类型不匹配: {}, 值: {}", applyTimeObj.getClass().getName(), applyTimeObj);
                }
            }
            
            // 处理create_time字段（用于CC任务）
            if (!timeSet && createTimeObj != null) {
                if (createTimeObj instanceof java.sql.Timestamp) {
                    vo.setCreateTime(((java.sql.Timestamp) createTimeObj).toLocalDateTime());
                    timeSet = true;
                } else if (createTimeObj instanceof java.time.LocalDateTime) {
                    vo.setCreateTime((java.time.LocalDateTime) createTimeObj);
                    timeSet = true;
                } else if (createTimeObj instanceof java.util.Date) {
                    vo.setCreateTime(((java.util.Date) createTimeObj).toInstant()
                        .atZone(java.time.ZoneId.systemDefault()).toLocalDateTime());
                    timeSet = true;
                } else {
                    log.debug("create_time字段类型不匹配: {}, 值: {}", createTimeObj.getClass().getName(), createTimeObj);
                }
            }
            
            // 如果两个时间字段都没设置成功，记录警告
            if (!timeSet) {
                log.warn("时间字段设置失败 - apply_time: {} ({}), create_time: {} ({})", 
                    applyTimeObj, applyTimeObj != null ? applyTimeObj.getClass().getName() : "null",
                    createTimeObj, createTimeObj != null ? createTimeObj.getClass().getName() : "null");
            }
            
            // 申请人信息（直接从SQL查询结果获取，避免循环查询）
            Object applicantIdObj = record.get("applicant_id");
            if (applicantIdObj != null) {
                vo.setApplicantId(((Number) applicantIdObj).longValue());
            }
            
            // 申请人详细信息（从SQL联表查询结果直接获取）
            vo.setApplicantName((String) record.get("applicant_name"));
            vo.setApplicantAvatar((String) record.get("applicant_avatar"));
            vo.setApplicantDepartment((String) record.get("applicant_department"));
            
            // 流程相关信息（从SQL联表查询结果直接获取）
            vo.setFlowType((String) record.get("flow_type"));
            vo.setProcesstype((String) record.get("process_type"));
            
            // 租户信息
            String sysTenantKey = (String) record.get("sys_tenant_key");
            vo.setSysTenantKey(sysTenantKey);
            // 暂时不查询租户名称，避免循环查询影响性能
            // vo.setSysTenantName(null);
            
            // 流程实例状态（默认为审批中）
            vo.setInstanceState(0);
            
            // 审批类型（默认为合同审批）
            vo.setApprovalType("合同审批");
            
            return vo;
            
        } catch (Exception e) {
            log.error("构建任务VO失败", e);
            return null;
        }
    }

    /**
     * 从SQL查询结果Map构建已处理任务VO - 不包含taskId和taskType
     */
    private PendingApprovalTaskVO buildProcessedTaskVOFromMap(Map<String, Object> record) {
        try {
            PendingApprovalTaskVO vo = buildTaskVOFromMap(record);
            if (vo == null) {
                return null;
            }
            
            // 对于已处理任务，移除taskId和taskType字段
            vo.setTaskId(null);
            vo.setTaskType(null);
            
            // 对于已处理任务，使用finish_time作为createTime
            if (record.get("finish_time") instanceof java.sql.Timestamp) {
                vo.setCreateTime(((java.sql.Timestamp) record.get("finish_time")).toLocalDateTime());
            }
            
            // 流程实例状态（已处理任务默认为完成状态）
            vo.setInstanceState(1);
            
            return vo;
            
        } catch (Exception e) {
            log.error("构建已处理任务VO失败", e);
            return null;
        }
    }

    /**
     * 从SQL查询结果Map构建抄送任务VO - 不包含taskId和taskType
     */
    private PendingApprovalTaskVO buildCcTaskVOFromMap(Map<String, Object> record) {
        try {
            PendingApprovalTaskVO vo = buildTaskVOFromMap(record);
            if (vo == null) {
                return null;
            }
            
            // 对于抄送任务，移除taskId和taskType字段
            vo.setTaskId(null);
            vo.setTaskType(null);
            
            // 时间信息已经在buildTaskVOFromMap中正确处理了（会使用create_time字段）
            log.debug("抄送任务构建完成，createTime: {}", vo.getCreateTime());
            
            // 流程实例状态（抄送任务默认为完成状态）
            vo.setInstanceState(1);
            
            // 如果有task_type字段，则设置为CC类型标识
            if (record.get("task_type") != null) {
                // 抄送任务的特殊标识，但不设置taskType字段
                log.debug("抄送任务类型: {}", record.get("task_type"));
            }
            
            return vo;
            
        } catch (Exception e) {
            log.error("构建抄送任务VO失败", e);
            return null;
        }
    }
}